<?php

namespace Drupal\custom_commerce\Plugin\Commerce\PromotionOffer;

use Drupal\commerce_order\Adjustment;
use Drupal\commerce_price\Price;
use Drupal\commerce_promotion\Entity\PromotionInterface;
use Drupal\commerce_promotion\Plugin\Commerce\PromotionOffer\OrderItemPercentageOff;
use Drupal\commerce_promotion\Plugin\Commerce\PromotionOffer\OrderPromotionOfferBase;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\multivalue_form_element\Element\MultiValue;

/**
 * @CommercePromotionOffer(
 *   id = "custom_commerce_custom_promotion",
 *   label = @Translation("Buy A and B get 50% on A+B"),
 *   entity_type = "commerce_order",
 * )
 */
class CustomPromotion extends OrderPromotionOfferBase {

  public function getIdsFromForm($form_state) {
    $info = $form_state->getUserInput();
    $items = $info['offer'][0]["target_plugin_configuration"]["custom_commerce_custom_promotion"]["items"][0][0];
    #$values = $form_state->getValue($form['items']);
    foreach ($items as $item) {
      if (!empty($item)) {
        $item_id = explode('(', $item);
        $item_id = end($item_id);
        $item_id = explode(')', $item_id);
        $id = $item_id[0];
        $ids[] = $id;
      }
    }
    return $ids;
  }
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);
    $ids = $this->getIdsFromForm($form_state);
    /*if (!empty($ids)) {
      foreach ($ids as $id_product_item) {
        $default_value = \Drupal::entityTypeManager()->getStorage('commerce_product')->load($id_product_item);
        $items[] = [
          '#type' => 'entity_autocomplete',
          '#target_type' => 'commerce_product',
          '#title' => 'Выберите товар',
          '#default_value' => !empty($default_value) ? $default_value : '',
        ];
      }
    } else {
      $items[] = [
        '#type' => 'entity_autocomplete',
        '#target_type' => 'commerce_product',
        '#title' => 'Выберите товар',
      ];
    }*/

    $items[] = [
      '#type' => 'entity_autocomplete',
      '#target_type' => 'commerce_product',
      '#title' => 'Выберите товар',
    ];

    $form['items'] = [
      '#type' => 'multivalue',
      '#title' => $this->t('Items'),
      '#cardinality' => MultiValue::CARDINALITY_UNLIMITED,
      'item' => [
        '#type' => 'entity_autocomplete',
        '#target_type' => 'commerce_product',
        '#title' => 'Выберите товар',
      ],
    ];

    return $form;
  }

  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    if (!$form_state->getErrors()) {
      $this->configuration['items'] = $this->getIdsFromForm($form_state);
    }
  }

  public function apply(EntityInterface $entity, PromotionInterface $promotion) {
    $this->assertEntity($entity);
    /** @var \Drupal\commerce_order\Entity\OrderItemInterface $order_item */
    $order = $entity;
    $first_item = $this->configuration['first_item'];
    $second_item = $this->configuration['second_item'];

    $items = $order->getItems();
    foreach ($items as $item) {
      $variation = $item->getPurchasedEntity();
      $id_product_item = $variation->getProductId();
      if ($id_product_item == $first_item) {
        $first_item_order = $item;
        $first_unit_price = $item->getUnitPrice()->toArray();
      }
      if ($id_product_item == $second_item) {
        $second_item_order = $item;
        $second_unit_price = $item->getUnitPrice()->toArray();
      }
    }
    if (!empty($first_item_order) and !empty($second_item_order)) {
      if ($first_item_order->getQuantity() >= $second_item_order->getQuantity()) {
        $quantity = $second_item_order->getQuantity();
      } else {
        $quantity = $first_item_order->getQuantity();
      }

      $discount_first_item = $first_unit_price['number'] * $quantity;
      $discount_second_item = $second_unit_price['number'] * $quantity;

      $price = New Price($discount_first_item + $discount_second_item, $first_unit_price['currency_code']);

      $order->addAdjustment(new Adjustment([
        'type' => 'promotion',
        'label' => 'custom discount',
        'amount' => $price->multiply(-0.5),
        'source_id' => $promotion->id(),
      ]));
    }
  }
}
