<?php

namespace FiloBlu\Storelocator\Controller\PickUpInStore;

use FiloBlu\Storelocator\Helper\Data;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Mail\Template\TransportBuilder;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Magento\Framework\Translate\Inline\StateInterface;
use Magento\Rma\Model\Rma;
use Magento\Rma\Model\Rma\Status\HistoryFactory;
use Magento\Rma\Model\RmaFactory;
use Magento\Store\Model\StoreManagerInterface;

/**
 *
 */
class RmarefusedAction extends Action
{
    /**
     * @var \FiloBlu\Storelocator\Helper\Data
     */
    protected $helper;
    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;
    /**
     * @var \Magento\Framework\App\ResourceConnection
     */
    private $resourceConnection;
    /**
     * @var \Magento\Framework\Controller\Result\JsonFactory
     */
    private $resultJsonFactory;
    /**
     * @var \Magento\Framework\Stdlib\DateTime\DateTime
     */
    private $date;

    /**
     * @var \Magento\Rma\Model\Rma\Status\HistoryFactory
     */
    private $historyFactory;

    /**
     * @param Context $context
     * @param JsonFactory $resultJsonFactory
     * @param Data $helper
     * @param HistoryFactory $historyFactory
     * @param DateTime $date
     * @param TransportBuilder $transportBuilder
     * @param StateInterface $inlineTranslation
     * @param ResourceConnection $resourceConnection
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(
        Context $context,
        JsonFactory $resultJsonFactory,
        Data $helper,
        HistoryFactory $historyFactory,
        DateTime $date,
        TransportBuilder $transportBuilder,
        StateInterface $inlineTranslation,
        ResourceConnection $resourceConnection,
        StoreManagerInterface $storeManager
    ) {
        $this->resultJsonFactory = $resultJsonFactory;
        $this->helper = $helper;
        $this->historyFactory = $historyFactory;
        $this->date = $date;
        $this->resourceConnection = $resourceConnection;
        $this->storeManager = $storeManager;
        parent::__construct($context);
    }

    /**
     * @return \Magento\Framework\Controller\Result\Json|\Magento\Framework\Controller\ResultInterface|void
     * @throws \Exception
     */
    public function execute()
    {

        $hash = $this->getRequest()->getParam('hash');
        $storeId = $this->storeManager->getStore()->getId();

        $isPickupInStoreEnabled = $this->helper->getPickupInStoreEnabled($storeId);
        $isReturnInStoreEnabled = $this->helper->getReturnToStoreEnabled($storeId);

        if ((!$isPickupInStoreEnabled && !$isReturnInStoreEnabled) || !$hash) {
            $this->_forward('noRoute');
            return;
        }

        // check if is rma or order request
        $rma = $this->helper->getRmaByHash($hash);

        if ($rma->getId() && $rma->getReturnToStoreHash() == $hash && (int)$rma->getReturnToStoreId() > 0) {
            $rma->setReturnToStoreReceivedDate($this->date->gmtDate());
            $rma->save();
            $resultJson = $this->resultJsonFactory->create();
            $resultJson->setData(
                [
                    'message' => __('You confirmed that the package ') . $rma->getData('increment_id') . __(
                            ' was rejected.'
                        )
                ]
            );
            $this->updateRma($rma);

            $this->_eventManager->dispatch('filoblu_storelocator_pickupinstore_rma_refused', ['rma' => $rma]);

            return $resultJson;
        }

        $this->_forward('noRoute');
    }

    /**
     * @param Rma |\Magento\Rma\Api\Data\RmaInterface $rma
     * @return void
     * @throws \Exception
     */
    public function updateRma($rma)
    {
        $connection = $this->resourceConnection->getConnection();
        $tableName = $this->resourceConnection->getTableName('magento_rma_item_entity');

        $query_rma_items = 'SELECT * FROM ' . $tableName . ' WHERE rma_entity_id = ' . $rma->getData('entity_id');
        $result = $connection->fetchAll($query_rma_items);
        foreach ($result as $item) {
            $item_id = $item['entity_id'];
            $qty_request = $item['qty_requested'];

            if ((int)$qty_request > 0) {
                $sql = 'UPDATE ' . $tableName . " SET status = '" . Rma\Source\Status::STATE_DENIED . "' WHERE entity_id = " . $item_id;

                $connection->query($sql);
            }
        }

        $rma->setStatus(Rma\Source\Status::STATE_CLOSED)->save();

        $comment = 'Return In Store - The package was rejected by store';

        $rmaHistory = $this->historyFactory->create();
        $rmaHistory->setRmaEntityId($rma->getId());
        $rmaHistory->setComment($comment);
        $rmaHistory->saveComment($comment, false, true);
    }
}
