<?php

namespace Drupal\mymodule\Plugin\Block;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\AlertCommand;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\mymodule\Form\TestForm;

/**
 * Provides
 *
 * @Block(
 *   id = "mymodule_products_suggest",
 *   admin_label = @Translation("Products"),
 *   context_definitions = {
 *     "node" = @ContextDefinition("entity:node", required = FALSE, label = @Translation("Node")),
 *   }
 * )
 */

class ProductsSuggest extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $node = $this->getContextValue('node');
    $node_id = $node->id();
    $card_id = 1;

    $products = \Drupal::entityTypeManager()
      ->getStorage('commerce_product')
      ->loadByProperties(['field_node' => $node_id]);
    foreach ($products as $product) {
      unset($card);
      $card['id'] = $card_id;
      $card['title'] = $product->label();
      $variations = $product->getVariations();

      foreach ($variations as $variation) {
        $card['price'][] = $variation->getPrice();
        $price = $variation->getPrice();
        $attribute = $variation->getAttributeValue('attribute_size');
        $card['options'][] = $attribute->label();
      }
      #$build[$card_id][] = $this->buildForm($card);
      #$build[] = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\ProductForm', $card);
      #$card_id++;
      $build[] = \Drupal::entityTypeManager()->getViewBuilder('commerce_product')->view($product, 'cart');
    }

    empty($products) ? $build = ['#markup' => 'Ничего не найдено'] : '';
    return $build;
  }

  public function buildForm($card) {
    $id = $card['id'];
    $build[$id]['card']['title'] = [
      '#type' => 'html_tag',
      '#tag' => 'h2',
      '#value' => $card['title'],
      '#attributes' => [
        'class' => ["card_title-$id"]
      ]
    ];

    $build[$id]['card']['price'] = [
      '#type' => 'html_tag',
      '#tag' => 'p',
      '#value' => $card['price'][0],
      '#attributes' => [
        'class' => ["card_price-$id"]
      ]
    ];

    $build[$id]['card']['form']['size'] = [
      '#type' => 'select',
      '#title' => 'Size',
      '#options' => $card['options'],
    ];

    $build[$id]['card']['form']['button'] = [
      '#type' => 'submit',
      '#value' => 'Добавить в корзину',
      '#attributes' => [
        'class' => ["card_button-$id"]
      ]
    ];
    return $build;
  }
}
