<?php
/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

namespace WriteTextAI\WriteTextAI\Helper\Categories;

use Magento\Framework\App\Helper\Context;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory as CategoryCollectionFactory;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    /**
     * @var CategoryCollectionFactory
     */
    protected $categoryCollectionFactory;

    /**
     * Constructor
     *
     * @param Context $context
     * @param CategoryCollectionFactory $categoryCollectionFactory
     */
    public function __construct(
        Context $context,
        CategoryCollectionFactory $categoryCollectionFactory
    ) {
        $this->categoryCollectionFactory = $categoryCollectionFactory;
        parent::__construct($context);
    }

    /**
     * Get breadcrumbs
     *
     * @param \Magento\Catalog\Model\Category $category
     * @param int $storeId
     *
     * @return array
     */
    public function getBreadcrumbs($category, $storeId)
    {
        $parentCategories = $category->getParentCategories();
        $totalParents = count($parentCategories);
        if ($totalParents <= 1) {
            return '';
        }

        $parentCategoriesIds = [];
        foreach ($parentCategories as $parent) {
            $parentCategoriesIds[] = $parent->getId();
        }

        $parentCategoriesData = $this->collectCategories($storeId, $parentCategoriesIds);

        $breadcrumbs = '<ul class="items">';
        foreach ($parentCategoriesData as $parentCategoryData) {
            if ($parentCategoryData->getEntityId() !== $category->getEntityId()) {
                $breadcrumbs .= '<li class="item">' . $parentCategoryData->getName() . '</li>';
            }
        }
        $breadcrumbs .= '</ul>';

        return $breadcrumbs;
    }

    /**
     * Collect categories
     *
     * @param int $storeId
     * @param array $categoryIds
     *
     * @return array
     */
    public function collectCategories($storeId, $categoryIds)
    {
        $collection = $this->categoryCollectionFactory->create();
        $collection->setStoreId($storeId);
        $collection->addAttributeToSelect('*');
        $collection->addFieldToFilter('entity_id', ['in' => $categoryIds]);

        $categories = [];
        foreach ($collection as $category) {
            $categories[$category->getId()] = $category;
        }

        return $categories;
    }
}
