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

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Grid;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Controller\ResultFactory;

class GetCustomizableOptionsWithValues extends Action
{
    /**
     * @var ProductRepositoryInterface
     */
    private $productRepository;

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

    /**
     * Get customizable options with values
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $result = $this->resultFactory->create(ResultFactory::TYPE_JSON);

        try {
            $storeId = (int) $this->getRequest()->getParam('store_id', 0);
            $recordIds = $this->getRequest()->getParam('record_ids', []);

            if (!is_array($recordIds)) {
                $recordIds = [$recordIds];
            }

            $recordIds = array_values(array_unique(array_filter(array_map('intval', $recordIds))));
            $recordIds = array_slice($recordIds, 0, 50);

            if (empty($recordIds)) {
                return $result->setData([
                    'success' => true,
                    'data' => [
                        'options' => []
                    ]
                ]);
            }

            $optionsMap = [];

            foreach ($recordIds as $recordId) {
                try {
                    $product = $this->productRepository->getById($recordId, false, $storeId);
                } catch (\Exception $e) {
                    continue;
                }

                if (!$product || !method_exists($product, 'getOptions')) {
                    continue;
                }

                $options = $product->getOptions();
                if (!is_array($options) || empty($options)) {
                    continue;
                }

                foreach ($options as $option) {
                    if (!$option || !method_exists($option, 'getOptionId')) {
                        continue;
                    }

                    $optionId = $option->getOptionId();
                    $optionId = is_numeric($optionId) ? (int) $optionId : 0;
                    if ($optionId <= 0) {
                        continue;
                    }

                    $values = [];
                    if (method_exists($option, 'getValues')) {
                        $values = $option->getValues();
                    }

                    if (!is_array($values) || empty($values)) {
                        continue;
                    }

                    $title = '';
                    if (method_exists($option, 'getTitle')) {
                        $title = trim((string) $option->getTitle());
                    }

                    if ($title === '') {
                        $title = 'Option #' . $optionId;
                    }

                    if (!isset($optionsMap[$optionId])) {
                        $optionsMap[$optionId] = [
                            'option_id' => $optionId,
                            'title' => $title
                        ];
                    }
                }
            }

            $options = array_values($optionsMap);
            usort($options, static function ($a, $b) {
                return ((int) ($a['option_id'] ?? 0)) <=> ((int) ($b['option_id'] ?? 0));
            });

            return $result->setData([
                'success' => true,
                'data' => [
                    'options' => $options
                ]
            ]);
        } catch (\Exception $e) {
            return $result->setData([
                'success' => false,
                'data' => [
                    'options' => []
                ]
            ]);
        }
    }
}
