<?php

namespace Drupal\basket\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Template\Attribute;
use Drupal\Component\Utility\Html;
use Drupal\Core\Url;

/**
 *
 * @Block(
 *   id = "basket_count",
 *   admin_label = @Translation("Basket count"),
 *   category = @Translation("Basket count"),
 * )
 */
class BasketCountBlock extends BlockBase {

	protected $basket;

	function __construct(){
		$this->basket = \Drupal::service('Basket');
	}
	public function build() {
		$Cart = $this->basket->Cart();
		$attributes = new Attribute([
			'class'		=> ['count-link']
		]);
	    if($this->basket->getSettings('order_page', 'config.view_ajax')){
	    	$attributes->setAttribute('href', 'javascript:void(0);');
	    	$attributes->setAttribute('onclick', 'basket_ajax_link(this, \''.Url::fromRoute('basket.pages', [
	    		'page_type'		=> 'api-load_popup'
	    	])->toString().'\')');
	    	$attributes->setAttribute('data-post', json_encode(['load_popup' => 'basket_view']));
	    } else {
	    	$attributes->setAttribute('href', Url::fromRoute('basket.pages', ['page_type' => 'view'])->toString());
	    }
	    $info = [
	    	'count'			=> $Cart->getCount(),
	    	'link'			=> [
	    		'text'			=> $this->basket->Translate()->t('Basket'),
	    		'attributes'	=> $attributes
	    	],
	    	'Cart'			=> $Cart,
	    ];
	    $info['countK']	= $this->basket->NumberFormat()->convert($info['count']);
	    return array(
	      	'#theme' 	=> 'basket_count_block',
	      	'#info'		=> $info,
	      	'#prefix'	=> '<div id="'.Html::getUniqueId('basket-count-block-wrap').'">',
	      	'#suffix'	=> '</div>',
	      	'#cache'	=> [
	      		'max-age'	=> 0
	      	],
	      	'#attached'	=> [
	      		'library'	=> ['basket/basket.js']
	      	]
	    );
	}
}