<?php

namespace Drupal\basket\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * User discount block.
 *
 * @Block(
 *   id = "basket_user_discount",
 *   admin_label = @Translation("Basket user discount percent"),
 *   category = @Translation("Basket user discount percent"),
 * )
 */
class BasketUserDiscountBlock extends BlockBase {

  /**
   * Set basket.
   *
   * @var Drupal\basket\Basket
   */
  protected $basket;

  /**
   * Set basketDiscount.
   *
   * @var Drupal\basket\Plugins\Discount\BasketDiscountManager
   */
  protected $basketDiscount;

  /**
   * {@inheritdoc}
   */
  public function __construct() {
    call_user_func_array(['parent', '__construct'], func_get_args());
    $this->basket = \Drupal::getContainer()->get('Basket');
    $this->basketDiscount = \Drupal::getContainer()->get('BasketDiscount');
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    return [
      '#theme'        => 'basket_user_discount',
      '#info'            => [
        'percent'        => $this->getMaxPercent(),
      ],
      '#prefix'        => '<div id="basket_user_discount_wrap">',
      '#suffix'        => '</div>',
      '#cache'        => [
        'max-age'        => 0,
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getMaxPercent() {
    $items = $this->basket->cart()->getItemsInBasket();
    $userDiscounts = [0];
    if (empty($items)) {
      $items[] = (object) [];
    }

    $filter = array_filter($this->configuration['discounts'] ?? ['']);

    if (!empty($items)) {
      foreach ($items as $item) {
        $discounts = $this->basketDiscount->getDiscounts($item);

        if(!empty($filter)) {
          foreach ($discounts as $dKey => $discount) {
            if(empty($filter[$dKey])) {
              unset($discounts[$dKey]);
            }
          }
        }
        
        if(!empty($discounts)) {
          $max = max($discounts);
          $userDiscounts[(string)$max] = $max;
        }
      }
    }
    return max($userDiscounts);
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $options = [
      ''            => t('All')
    ];
    $actives = $this->basket->getSettings('discount_system', 'config');
    foreach ($this->basketDiscount->getDefinitions() as $service) {
      if (empty($actives[$service['id']]['active'])) {
        continue;
      }
      $options[$service['id']] = $this->basket->Translate($service['provider'])->trans(trim($service['name']));
    }
    $form['discounts'] = [
      '#type'           => 'checkboxes',
      '#title'          => $this->basket->translate()->t('Discount system'),
      '#options'        => $options,
      '#default_value'  => $this->configuration['discounts'] ?? ['']
    ];
    foreach ($options as $k => $option) {
      switch ($k) {
        case '':

          break;
        default:
          $form['discounts'][$k]['#states']['disabled'] = [
            'input[name="settings[discounts][]"]' => ['checked' => TRUE]
          ];
          $form['discounts']['']['#states']['disabled'][]['input[name="settings[discounts]['.$k.']"]'] = ['checked' => TRUE];
          break;
      }
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    if (!$form_state->getErrors()){
      $this->configuration['discounts'] = $form_state->getValue('discounts');
    }
  }

}
