<?php

namespace Autogedal\Extend\Model;

use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\Exception\NoSuchEntityException;

class CategoryHierarchy extends AbstractHelper
{
    /**
     * @var CategoryRepositoryInterface
     */
    protected $categoryRepository;

    /**
     * @var ProductRepositoryInterface
     */
    protected $productRepository;

    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @param Context $context
     * @param CategoryRepositoryInterface $categoryRepository
     * @param ProductRepositoryInterface $productRepository
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(
        Context $context,
        CategoryRepositoryInterface $categoryRepository,
        ProductRepositoryInterface $productRepository,
        StoreManagerInterface $storeManager
    ) {
        parent::__construct($context);
        $this->categoryRepository = $categoryRepository;
        $this->productRepository = $productRepository;
        $this->storeManager = $storeManager;
    }

    public function getCategoryHierarchyByProduct($product, $separator = ' > ', $storeId = null)
    {
        try {
            if ($storeId === null) {
                $storeId = $this->storeManager->getStore()->getId();
            }

            $categoryIds = $product->getCategoryIds();

            if (empty($categoryIds)) {
                return null;
            }

            $deepestCategory = $this->getDeepestCategory($categoryIds, $storeId);
            
            if (!$deepestCategory) {
                return null;
            }

            return $this->buildCategoryPath($deepestCategory, $separator, $storeId);

        } catch (NoSuchEntityException $e) {
            $this->_logger->error('Product not found: ' . $e->getMessage());
            return null;
        } catch (\Exception $e) {
            $this->_logger->error('Error getting category hierarchy: ' . $e->getMessage());
            return null;
        }
    }


    /**
     * Find the deepest category from category IDs
     *
     * @param array $categoryIds
     * @param int $storeId
     * @return \Magento\Catalog\Api\Data\CategoryInterface|null
     */
    protected function getDeepestCategory($categoryIds, $storeId)
    {
        $deepestCategory = null;
        $maxLevel = 0;

        foreach ($categoryIds as $categoryId) {
            try {
                $category = $this->categoryRepository->get($categoryId, $storeId);
                
                // Skip root category and default category
                if ($category->getLevel() <= 1) {
                    continue;
                }

                if ($category->getLevel() > $maxLevel) {
                    $maxLevel = $category->getLevel();
                    $deepestCategory = $category;
                }
            } catch (NoSuchEntityException $e) {
                continue;
            }
        }

        return $deepestCategory;
    }

    /**
     * Build category path string
     *
     * @param \Magento\Catalog\Api\Data\CategoryInterface $category
     * @param string $separator
     * @param int $storeId
     * @return string
     */
    protected function buildCategoryPath($category, $separator, $storeId)
    {
        $path = [];
        $currentCategory = $category;

        while ($currentCategory && $currentCategory->getLevel() > 1) {
            array_unshift($path, $currentCategory->getName());
            
            $parentId = $currentCategory->getParentId();
            if ($parentId && $parentId > 1) {
                try {
                    $currentCategory = $this->categoryRepository->get($parentId, $storeId);
                } catch (NoSuchEntityException $e) {
                    break;
                }
            } else {
                break;
            }
        }

        array_unshift($path, "Accesorii auto");
        return implode($separator, $path);
    }
}
