<?php

declare(strict_types=1);

namespace Autogedal\Labels\Model\Config\Source;

use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory;
use Magento\Framework\Data\OptionSourceInterface;

/**
 * Category tree options with M1-style hyphen indentation (e.g. "------Pacnete").
 */
class CategoryTree implements OptionSourceInterface
{
    /**
     * @var CollectionFactory
     */
    private $categoryCollectionFactory;

    public function __construct(CollectionFactory $categoryCollectionFactory)
    {
        $this->categoryCollectionFactory = $categoryCollectionFactory;
    }

    /**
     * @return array
     */
    public function toOptionArray(): array
    {
        $options = [];

        $collection = $this->categoryCollectionFactory->create();
        $collection->addAttributeToSelect('name')
            ->addAttributeToSort('level', \Magento\Framework\Data\Collection::SORT_ORDER_ASC)
            ->addAttributeToSort('position', \Magento\Framework\Data\Collection::SORT_ORDER_ASC)
            ->addAttributeToSort('path', \Magento\Framework\Data\Collection::SORT_ORDER_ASC);

        foreach ($collection as $category) {
            $level = (int)$category->getLevel();
            // Skip root (level 0) and default store root (level 1) so we only show real categories
            if ($level < 2) {
                continue;
            }
            $hyphens = str_repeat('-', (int)(($level - 1) * 2));
            $label = $hyphens . $category->getName();
            $options[] = [
                'label' => $label,
                'value' => (string)$category->getId(),
            ];
        }

        return $options;
    }
}
