<?php
namespace FiloBlu\Rma\Block\Adminhtml\Order\View\Tab\ChangeSizeOrders;

use FiloBlu\Rma\Block\Adminhtml\Order\View\Tab\ChangeSizeOrders\Renderer\Link;
use Magento\Backend\Block\Template\Context;
use Magento\Backend\Block\Widget\Grid\Column\Filter\Datetime;
use Magento\Backend\Block\Widget\Grid\Extended;
use Magento\Backend\Helper\Data;
use Magento\Framework\Registry;

/**
 *
 */
class Grid extends Extended
{
    /**
     * @var \Magento\Framework\Data\CollectionFactory|\Magento\Rma\Model\ResourceModel\Rma\CollectionFactory
     */
    protected $_collectionFactory;
    /**
     * @var Registry
     */
    private $registry;

    /**
     * @param Context $context
     * @param Data $backendHelper
     * @param Registry $registry
     * @param \Magento\Rma\Model\ResourceModel\Rma\CollectionFactory $collectionFactory
     * @param array $data
     */
    public function __construct(
        Context $context,
        Data $backendHelper,
        Registry $registry,
        \Magento\Rma\Model\ResourceModel\Rma\CollectionFactory $collectionFactory,
        array $data = []
    ) {
        $this->_collectionFactory = $collectionFactory;
        parent::__construct($context, $backendHelper, $data);
        $this->setId('change_size_orders_grid');
        $this->setDefaultSort('entity_id');
        $this->setDefaultDir('ASC');
        $this->setSaveParametersInSession(true);
        $this->setUseAjax(true);
        $this->registry = $registry;
    }

    /**
     * @return \FiloBlu\Rma\Block\Adminhtml\Order\View\Tab\ChangeSizeOrders\Grid
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    protected function _prepareCollection()
    {
        $order = $this->getOrder();

        $collection = $this->_collectionFactory->create();
        $collection->getSelect()->distinct(true);
        $collection->addFieldToFilter('main_table.order_id', ['eq' => $order->getEntityId()]);
        $collection->addFieldToSelect([
            'rma_increment_id' => 'increment_id'
        ]);
        $collection->getSelect()->joinLeft(
            ['sop' => 'sales_order_payment'],
            'sop.additional_information ->> "$.parent_order_id" = main_table.order_id and sop.`method` = "changesizepay"',
            []
        );
        $collection->getSelect()->joinLeft(
            ['mrie' => 'magento_rma_item_entity'],
            'main_table.entity_id = mrie.rma_entity_id',
            []
        );
        $collection->getSelect()->joinLeft(
            ['fri' => 'filoblu_rma_items'],
            'fri.rma_item_id = mrie.entity_id',
            []
        );
        $collection->getSelect()->joinRight(
            ['so' => 'sales_order'],
            'fri.order_id = so.entity_id',
            ['so.increment_id', 'so.status', 'so.created_at']
        );

        // Specify the order of fields in the select
        $collection->getSelect()->reset(\Zend_Db_Select::COLUMNS);
        $collection->getSelect()->columns([
            'cs_increment_id' => 'so.increment_id',       // Column from joined table
            'rma_increment_id' => 'main_table.entity_id',       // Column from joined table
            'main_table.increment_id',       // Column from main table
            'child_order_id' => 'so.entity_id', // Column from main table
            'so.status', // Column from main table
            'so.created_at', // Column from main table
        ]);

        $this->setCollection($collection);

        return parent::_prepareCollection();
    }

    /**
     * @return \FiloBlu\Rma\Block\Adminhtml\Order\View\Tab\ChangeSizeOrders\Grid
     * @throws \Exception
     */
    protected function _prepareColumns()
    {
        $this->addColumn('cs_increment_id', [
            'header' => __('Order ID'),
            'index' => 'cs_increment_id',
        ]);

        $this->addColumn('rma_increment_id', [
            'header' => __('Rma ID'),
            'index' => 'rma_increment_id',
        ]);

        $this->addColumn('status', [
            'header' => __('Order Status'),
            'index' => 'status',
        ]);

        $this->addColumn('created_at', [
            'header' => __('Creation Date'),
            'index' => 'created_at',
            'type' => 'datetime', // Use 'date' or 'datetime' depending on your needs
            'renderer' => \Magento\Backend\Block\Widget\Grid\Column\Renderer\Datetime::class,
            'filter' => Datetime::class,
        ]);

        $this->addColumn('view_link', [
            'header' => __('Action'),
            'renderer' => Link::class,
            'filter' => false,
            'sortable' => false,
        ]);

        return parent::_prepareColumns();
    }

    /**
     * @return mixed|null
     */
    public function getOrder()
    {
        return $this->registry->registry('current_order');
    }
}
