<?php
namespace FiloBlu\Rma\Ui\Component\Listing\Columns\ChangeSizeItems;

use FiloBlu\Rma\Helper\ChangeSizeOrder;
use Magento\Backend\Model\UrlInterface;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Rma\Model\RmaRepository;
use Magento\Ui\Component\Listing\Columns\Column;

class IsEasyReturn extends Column
{
    protected $urlBuilder;
    /**
     * @var ChangeSizeOrder
     */
    private $changeSizeOrderHelper;
    /**
     * @var \Magento\Rma\Model\RmaRepository
     */
    private $rmaRepository;

    /**
     * @param ContextInterface $context
     * @param UiComponentFactory $uiComponentFactory
     * @param UrlInterface $urlBuilder
     * @param ChangeSizeOrder $changeSizeOrderHelper
     * @param RmaRepository $rmaRepository
     * @param array $components
     * @param array $data
     */
    public function __construct(
        ContextInterface   $context,
        UiComponentFactory $uiComponentFactory,
        UrlInterface       $urlBuilder,
        ChangeSizeOrder    $changeSizeOrderHelper,
        RmaRepository $rmaRepository,
        array              $components = [],
        array              $data = []
    ) {
        $this->urlBuilder = $urlBuilder;
        parent::__construct($context, $uiComponentFactory, $components, $data);
        $this->changeSizeOrderHelper = $changeSizeOrderHelper;
        $this->rmaRepository = $rmaRepository;
    }

    public function prepareDataSource(array $dataSource)
    {
        if (isset($dataSource['data']['items'])) {
            foreach ($dataSource['data']['items'] as & $item) {

                 $hidden = false;

                $rma = $this->rmaRepository->get($item['rma_id']);

                if ($this->changeSizeOrderHelper->getOrderItemsByRma($rma)) {
                    $hidden = true;
                }

                // Aggiungi la logica per determinare se il pulsante deve essere visualizzato o meno
                $item[$this->getData('name')] = [
                    'edit' => [
                        'href' => $this->urlBuilder->getUrl('filoblu_rma/changesizeitems/generateorders/id/' . $item['item_id']),
                        'label' => __('Generate CS Order'),
                        'hidden' => $hidden, // Imposta a true se il pulsante non deve essere mostrato
                    ],
                ];
            }
        }

        return $dataSource;
    }
}
