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

declare(strict_types=1);

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Grid;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use Magento\Store\Model\Store;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory as CategoryCollectionFactory;
use WriteTextAI\WriteTextAI\Model\OptionSource\Filter\Categories as CategoriesOptionSource;

class CategoriesOptions extends Action
{
    public const ADMIN_RESOURCE = 'WriteTextAI_WriteTextAI::menu';

    /**
     * @var CategoryCollectionFactory
     */
    private $categoryCollectionFactory;

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    private $storeManager;

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

    /**
     * Execute action
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $result = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        
        try {
            $storeId = (int)$this->getRequest()->getParam('store_id', Store::DEFAULT_STORE_ID);
    
            if ($storeId > 0) {
                $store = $this->storeManager->getStore($storeId);
                $rootCategoryId = $store->getRootCategoryId();

                $collection = $this->categoryCollectionFactory->create();
                $collection->setStoreId($storeId);
                $collection->addAttributeToSelect('name');
                $collection->addAttributeToSelect('parent_id');
                $collection->addFieldToFilter('level', ['gteq' => 0]);
                $collection->addFieldToFilter('entity_id', ['neq' => 1]);
                $collection->getSelect()->where("path = '1/{$rootCategoryId}' OR path LIKE '1/{$rootCategoryId}/%'");
                $collection->setOrder('entity_id', 'ASC');
            } else {
                $collection = $this->categoryCollectionFactory->create();
                $collection->setStoreId(0);
                $collection->addAttributeToSelect('name');
                $collection->addAttributeToSelect('parent_id');
                $collection->addFieldToFilter('level', ['gteq' => 0]);
                $collection->addFieldToFilter('entity_id', ['neq' => 1]);
                $collection->setOrder('entity_id', 'ASC');
            }
            
            $nodes = [];
            foreach ($collection as $category) {
                $categoryId = (int)$category->getId();
                $nodes[$categoryId] = [
                    'id' => $categoryId,
                    'parent_id' => (int)$category->getParentId(),
                    'label' => (string)$category->getName(),
                    'level' => (int)$category->getLevel(),
                    'children' => []
                ];
            }

            $roots = [];
            foreach ($nodes as $categoryId => $node) {
                $parentId = $node['parent_id'];
                if (isset($nodes[$parentId])) {
                    $nodes[$parentId]['children'][] = $categoryId;
                } else {
                    $roots[] = $categoryId;
                }
            }

            $buildOptions = function (array $ids) use (&$buildOptions, $nodes): array {
                $options = [];
                foreach ($ids as $id) {
                    if (!isset($nodes[$id])) {
                        continue;
                    }

                    $node = $nodes[$id];
                    $option = [
                        'label' => $node['label'],
                        'value' => (int)$node['id'],
                        'level' => $node['level'] // Add level to option
                    ];

                    if (!empty($node['children'])) {
                        $option['optgroup'] = $buildOptions($node['children']);
                    }

                    $options[] = $option;
                }

                return $options;
            };

            $result->setData([
                'success' => true,
                'options' => array_merge($buildOptions($roots), [
                    [
                        'label' => (string)__('No Category'),
                        'value' => CategoriesOptionSource::NO_CATEGORY_VALUE
                    ]
                ])
            ]);
        } catch (\Exception $e) {
            $message = $e->getMessage();
            if (!$message) {
                $message = __(
                    'A system error has occurred. Please try again. If the issue persists,'
                    . ' please contact our support team at support@writetext.ai.'
                );
            }

            $result->setData([
                'success' => false,
                'message' => $message
            ]);
        }

        return $result;
    }
}
