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

use FiloBlu\Rma\Helper\ChangeSizeItemsHelper;
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 GenerateChangeSizeOrder extends Column
{
    protected $urlBuilder;
    /**
     * @var ChangeSizeOrder
     */
    private $changeSizeOrderHelper;
    /**
     * @var RmaRepository
     */
    private $rmaRepository;
    /**
     * @var ChangeSizeItemsHelper
     */
    private $changeSizeItemsHelper;

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

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

                $hidden = true;

                if ($this->changeSizeItemsHelper->needToGenerateChangeSizeOrder($item)) {
                    $hidden = false;
                }

                // 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;
    }
}
