<?php

namespace Leadlion\Autogedal\Block;

use Magento\Catalog\Helper\Data;
use Magento\Framework\View\Element\Template\Context;
use Magento\Store\Model\Store;
use Magento\Framework\Registry;

class Breadcrumbs extends \Magento\Theme\Block\Html\Breadcrumbs
{
    /**
     * Catalog data
     *
     * @var Data
     */
    protected $_catalogData = null;

    /**
     * Catalog data
     *
     * @var \Leadlion\Autogedal\Helper\Config
     */
    protected $helperConfig;

    /**
     * Helper Url
     *
     * @var \Amasty\ShopbySeo\Helper\Url
     */
    protected $helperUrl;

    /**
     * @param Context $context
     * @param Data $catalogData
     * @param array $data
     */
    public function __construct(
        Context $context,
        Data $catalogData,
        Registry $registry,
        \Leadlion\Autogedal\Helper\Config $helperConfig,
        \Amasty\ShopbySeo\Helper\Url $helperUrl,
        array $data = []
    ) {
        $this->_catalogData = $catalogData;
        $this->registry = $registry;
        $this->helperConfig = $helperConfig;
        $this->helperUrl = $helperUrl;
        parent::__construct($context, $data);
    }

    /**
     * Retrieve HTML title value separator (with space)
     *
     * @param null|string|bool|int|Store $store
     * @return string
     */
    public function getTitleSeparator($store = null)
    {
        $separator = (string)$this->_scopeConfig->getValue('catalog/seo/title_separator', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $store);
        return ' ' . $separator . ' ';
    }
    
    public function getCrumbs() {
        return $this->_crumbs;
    }

    /**
     * Preparing layout
     *
     * @return \Magento\Catalog\Block\Breadcrumbs
     */
    protected function _prepareLayout()
    {
        $title = [];
        if ($breadcrumbsBlock = $this->getLayout()->getBlock('breadcrumbs')) {
            $breadcrumbsBlock->addCrumb(
                'home', [
                    'label' => __('Cars accessoris'),
                    'title' => __('Go to Home Page'),
                    'link' => $this->_storeManager->getStore()->getBaseUrl()
                ]
            );
            $path = $this->_catalogData->getBreadcrumbPath();
            $product = $this->registry->registry('current_product');

            if ($product && count($path) == 1) {
                $categoryCollection = clone $product->getCategoryCollection();
                $categoryCollection->clear();
                $categoryCollection->addAttributeToSort('level', $categoryCollection::SORT_ORDER_DESC)->addAttributeToFilter('path', array('like' => "1/" . $this->_storeManager->getStore()->getRootCategoryId() . "/%"));
                $categoryCollection->setPageSize(1);
                $breadcrumbCategories = $categoryCollection->getFirstItem()->getParentCategories();
                
                $catbreadcrumb = [];
                foreach ($breadcrumbCategories as $category) {
                    $catbreadcrumb = array("label" => $category->getName(), "link" => $category->getUrl());
                    $breadcrumbsBlock->addCrumb("category" . $category->getId(), $catbreadcrumb);
                    $title[] = $category->getName();
                }
                $this->addFiltersInProductCrumbs($breadcrumbsBlock, $product, $catbreadcrumb);
                //add current product to breadcrumb
                $prodbreadcrumb = array("label" => $product->getName(), "link" => "");
                $breadcrumbsBlock->addCrumb("product" . $product->getId(), $prodbreadcrumb);
                $title[] = $product->getName();
            } else {
                foreach ($path as $name => $breadcrumb) {
                    if ($name == 'product') {
                        foreach ($path as $name => $breadcrumb) {
                            if (strpos($name, 'category') === 0) {
                                $this->addFiltersInProductCrumbs($breadcrumbsBlock, $product, $breadcrumb);
                            }
                        }
                    }
                    $breadcrumbsBlock->addCrumb($name, $breadcrumb);
                    $title[] = $breadcrumb['label'];
                }
            }
            $this->pageConfig->getTitle()->set(join($this->getTitleSeparator(), array_reverse($title)));
            return parent::_prepareLayout();
        }
        $path = $this->_catalogData->getBreadcrumbPath();
        foreach ($path as $name => $breadcrumb) {
            $title[] = $breadcrumb['label'];
        }
        $this->pageConfig->getTitle()->set(join($this->getTitleSeparator(), array_reverse($title)));
        return parent::_prepareLayout();
    }

    protected function addFiltersInProductCrumbs($breadcrumbsBlock, $product, $catbreadcrumb = null)
    {
        $allowebBreadcrumbsFilters = $this->helperConfig->getConfig('leadlion/layer_navigation/filters');
        if ($allowebBreadcrumbsFilters &&
            $product
        ) {
            $allBreadFiltArray = explode(',', $allowebBreadcrumbsFilters);
            foreach ($allBreadFiltArray as $key => $allowedFilter) {
                $params = '';
                if ($key == 0) {
                    $params = '?'.$allowedFilter.'='.$product->getData($allowedFilter);
                }
                if ($key > 0) {
                    foreach ($allBreadFiltArray as $insideKey => $insideFilterCode) {
                        if ($insideKey <= $key) {
                            if ($insideKey == 0) {
                                $params =
                                    '?'.$insideFilterCode.'='.$product->getData($insideFilterCode);
                            } else {
                                $params .=
                                    '&'.$insideFilterCode.'='.$product->getData($insideFilterCode);
                            }
                        }
                    }
                }

                //add allowed filters into breadcrumb
                $breadcrumbName = $product->getAttributeText($allowedFilter);
                if ($breadcrumbName) {
                    $seoUrl = '';
                    if (isset($catbreadcrumb['link'])) {
                        $seoUrl = $this->helperUrl->seofyUrl(
                            $catbreadcrumb['link'].$params
                        );
                    }
                    
                    $allowedFilterCrumb = ["label" => $breadcrumbName, "link" => $seoUrl];
                    $breadcrumbsBlock->addCrumb($breadcrumbName, $allowedFilterCrumb);
                }
            }
        }
    }
}
