<?php

namespace Drupal\basket\Plugin\Basket\Discount;

use Drupal\basket\Plugins\Discount\Annotation\BasketDiscount;
use Drupal\basket\Plugins\Discount\BasketDiscountInterface;
use Drupal\Core\Url;

/**
 * @BasketDiscount(
 *          id        = "discount_range",
 *          name      = "Discount on the total amount of the order",
 * )
 */
class DiscountRange implements BasketDiscountInterface {

	protected static $Basket;
	protected static $Config;

	function __construct(){
		self::$Basket = \Drupal::service('Basket');
	}
	// Получаем ссылку на редактирование
	public function settingsLink(){
		return [
			'#type'			=> 'link',
			'#title'		=> self::$Basket->Translate()->t('Settings page'),
			'#url'			=> new Url('basket.admin.pages', [
				'page_type'		=> 'settings-discount_range'
			], [
				'attributes'	=> [
					'class'			=> ['button--link target']
				],
				'query'			=> \Drupal::destination()->getAsArray()
			])
		];
	}
	// Скидка на отдельную позицию корзины
	public function discountItem($item){
		$percent = 0;
		$config = self::getConfig();
		if(!empty($config)){
			$totalSum = self::$Basket->Cart()->getTotalSum(TRUE, TRUE);
			if(self::$Basket->Currency()->getCurrent(TRUE) != self::$Basket->Currency()->getCurrent(FALSE)){
				$currencyCurrent = self::$Basket->Currency()->getCurrent(FALSE);
				self::$Basket->Currency()->PriceConvert($totalSum, $currencyCurrent, TRUE);
			}
			if(!empty($totalSum)){
				foreach ($config as $row){
					if(!empty($row['min']) && $row['min'] <= $totalSum && !empty($row['percent'])){
						if(!empty($row['max'])){
                            if($row['max'] >= $totalSum){
                                $percent = $row['percent'];
                            }
                        } else {
                            $percent = $row['percent'];                  
                        }
					}
				}
			}
		}
		return $percent;
	}
	private static function getConfig(){
		if(!self::$Config){
			self::$Config = self::$Basket->getSettings('discount_range', 'config');
		}
		return self::$Config;
	}
}