<?php

namespace Drupal\basket\Admin;

use \Drupal\Core\Render\Markup;
use \Drupal\Core\Url;

class ManagerHeader{

	protected $current_rout_name;
    protected $current_rout_params;
    protected $basket;

    function __construct(){
        $this->basket = \Drupal::service('Basket');
        $this->current_rout_name = \Drupal::routeMatch()->getRouteName();
        $this->current_rout_params = \Drupal::routeMatch()->getParameters()->all();
    }

	public function block($CreateLink = []){
        return [
        	'#theme'		=> 'basket_admin_header',
        	'#info'			=> [
        		'breadcrumbs' => $this->getBreadcrumbs(),
        		'items'		 => [
                    [
                        'block'     => \Drupal::service('plugin.manager.block')->createInstance('basket_currency')->build()
                    ],[
    					'#type'		=> 'link',
    					'#title'       => $this->basket->Translate()->t('To the site'),
    					'#url'		=> new Url('<front>', [], [
    						'ico_name'	=> 'home.svg'
    					])
    				],[
    					'#type'		=> 'link',
    					'#title'   => $this->basket->Translate()->t('Exit'),
    					'#url'		=> new Url('user.logout', [], [
    						'ico_name'	=> 'user.svg'
    					])
    				]
        		],
                'CreateLink'    => $CreateLink
        	]
        ];
  	}
  	private function getBreadcrumbs(){
  		$items = [];
  		$this->getBreadcrumbsItems($items);
  		return !empty($items) ? array_reverse($items) : [];
  	}
  	private function getBreadcrumbsItems(&$items, $parent_id = NULL){
  		$query = \Drupal::database()->select('menu_tree', 'm');
  		$query->fields('m', ['parent', 'title', 'id']);
  		if(is_null($parent_id)){
	  		$query->condition('route_name', $this->current_rout_name);
	  		if(!empty($this->current_rout_params['page_type'])){
	  			$query->condition('route_param_key', 'page_type='.$this->current_rout_params['page_type']);
	  		}
            $query->condition('m.parent', '', '!=');
  		} else {
  			$query->condition('m.id', $parent_id);
  		}
  		$get_info = $query->execute()->fetchObject();
  		if(!empty($get_info)){
  			$items[] = unserialize($get_info->title);
  			if(!empty($get_info->parent)){
  				$this->getBreadcrumbsItems($items, $get_info->parent);
  			}
  		}
  	}
}