<?php
namespace Autogedal\BlogInternalLinking\Model\Source;

use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory;
use Magento\Framework\Option\ArrayInterface;

class Category implements ArrayInterface
{
    private $collectionFactory;
    private $options;

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

    public function toOptionArray(): array
    {
        if ($this->options !== null) {
            return $this->options;
        }

        $collection = $this->collectionFactory->create();
        $collection->addAttributeToSelect('name')
            ->addAttributeToFilter('is_active', 1)
            ->addAttributeToFilter('level', ['gt' => 1])
            ->setOrder('path', 'ASC');

        $this->options = [];
        foreach ($collection as $category) {
            $indent = str_repeat('— ', max(0, (int)$category->getLevel() - 2));
            $this->options[] = [
                'value' => $category->getId(),
                'label' => $indent . $category->getName() . ' [' . $category->getId() . ']',
            ];
        }

        return $this->options;
    }
}
