<?php

namespace Drupal\custom_commerce\Controller;

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

class ProductsAutoCompleteController extends ControllerBase {

  protected $productStorage;

  /**
   * {@inheritdoc}
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->productStorage = $entity_type_manager->getStorage('commerce_product');
  }

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

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

    if (!$input) {
      return new JsonResponse($results);
    }

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

    $query = $this->productStorage->getQuery()
      ->condition('bundle', $input, 'CONTAINS');
      ->condition('title', $input, 'CONTAINS')
      ->sort('created', 'DESC')
      ->range(0, 10);

    $ids = $query->execute();
    $orderItems = $ids ? $this->productStorage->loadMultiple($ids) : [];

    foreach ($orderItems as $orderItem) {
      switch ($orderItem->isPublished()) {
        case TRUE:
          $availability = '✅';
          break;

        case FALSE:
        default:
          $availability = '🚫';
          break;
      }

      $label = [
        $orderItem->getTitle(),
        '<small>(' . $node->id() . ')</small>',
        $availability,
      ];

      $results[] = [
        'value' => EntityAutocomplete::getEntityLabels([$node]),
        'label' => implode(' ', $label),
      ];
    }

    return new JsonResponse($results);*/
  }
}
