<?php

namespace Drupal\mymodule\Form;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\AlertCommand;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class ProductForm extends FormBase {
  public $id;
  public $prices;

  public function getFormId() {
    return 'mymodule_product_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state, $card = NULL) {
    $this->prices = $card['price'];
    $id = $card['id'];

    $form[$id]['card']['title'] = [
      '#type' => 'html_tag',
      '#tag' => 'h2',
      '#value' => $card['title'],
      '#attributes' => [
        'class' => ["card_title-$id"]
      ]
    ];

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

    $form[$id]['card']['form']['size'] = [
      '#type' => 'select',
      '#title' => 'Size',
      '#options' => $card['options'],
      '#ajax' => [
        'callback' => '::changePrice',
        'event' => 'change',
      ],
    ];

    $form[$id]['card']['form']['button'] = [
      '#type' => 'submit',
      '#value' => 'Добавить в корзину',
      '#ajax' => [
        'callback' => '::alert',
        'event' => 'click',
      ],
      '#attributes' => [
        'class' => ["card_button-$id"]
      ]
    ];

    return $form;
  }

  public function SubmitForm(array &$form, FormStateInterface $form_state) {

  }

  public function changePrice(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $count = $form_state->getValue('size');
    $price = $this->prices;
    $response->addCommand(new HtmlCommand(".card_price-$this->id", "$price[$count]"));
    return $response;
  }

  public function alert(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $response->addCommand(new AlertCommand('Hello'));
    return $response;
  }
}
