<?php

namespace Drupal\basket\Plugin\Basket\Discount\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class DiscountRangeForm extends FormBase{
	
    protected static $Basket;
    protected static $Currency = '';
    protected static $CurrencyID = 0;
    const MAX_NUM = 10;

	public function __construct(){
		self::$Basket = \Drupal::service('Basket');
		self::$CurrencyID = self::$Basket->Currency()->getCurrent(TRUE);
		if(!empty(self::$CurrencyID)){
			$defCurrency = self::$Basket->Currency()->load(self::$CurrencyID);
			self::$Currency = self::$Basket->Translate()->t($defCurrency->name);
		}
	}
	public function getFormId(){
    	return 'basket_discount_range_settings';
  	}
  	public function buildForm(array $form, FormStateInterface $form_state){
        $form['config'] = [
        	'#type'			=> 'table',
        	'#header'		=> [
        		'',
        		self::$Basket->Translate()->t('Price from').' ('.self::$Currency.')',
        		self::$Basket->Translate()->t('Price to').' ('.self::$Currency.')',
        		'%'
        	]
        ];
        foreach (range(1, $this::MAX_NUM) as $key){
        	$form['config'][$key] = [
        		'num'           => [
                    '#markup'       => $key
                ],
                'min'			=> [
                	'#type'			=> 'number',
                	'#field_suffix'	=> '',
                	'#min'			=> 0,
                	'#default_value'=> self::$Basket->getSettings('discount_range', 'config.'.$key.'.min')
                ],
                'max'			=> [
                	'#type'			=> 'number',
                	'#field_suffix'	=> '',
                	'#min'			=> 0,
                	'#default_value'=> self::$Basket->getSettings('discount_range', 'config.'.$key.'.max')
                ],
                'percent'		=> [
                	'#type'			=> 'select',
                	'#options'		=> array_combine(range(0, 100), range(0, 100)),
                	'#default_value'=> self::$Basket->getSettings('discount_range', 'config.'.$key.'.percent')
                ]
        	];
        }
        $form['actions'] = [
            '#type'         => 'actions',
            'submit'        => [
                '#type'         => 'submit',
                '#value'        => self::$Basket->Translate()->t('Save')
            ]
        ];
        return $form;
  	}
  	public function submitForm(array &$form, FormStateInterface $form_state){
        $form_state->setValue(['config', 'CurrencyID'], self::$CurrencyID);
       	self::$Basket->setSettings('discount_range', 'config', $form_state->getValue('config'));
    }
}