<?php

namespace FiloBlu\Storelocator\Controller\PickUpInStore;


use Exception;
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\Stdlib\DateTime\DateTime;
use Magento\Rma\Model\Rma;
use Magento\Rma\Model\Rma\Status\HistoryFactory;
use Magento\Rma\Model\RmaFactory;
use Magento\Store\Model\StoreManagerInterface;
use Psr\Log\LoggerInterface;

/**
 *
 */
class RmareceivedAction extends Action
{
    /**
     * @var \FiloBlu\Storelocator\Helper\Data
     */
    protected $helper;
    /**
     * @var StoreManagerInterface
     */
    protected $storeManager;
    /**
     * @var Context
     */
    protected $context;

    /**
     * @var \Magento\Framework\App\ResourceConnection
     */
    private $resourceConnection;

    /**
     * @var \Magento\Framework\Controller\Result\JsonFactory
     */
    private $resultJsonFactory;
    /**
     * @var \Magento\Framework\Stdlib\DateTime\DateTime
     */
    private $date;
    /**
     * @var \FiloBlu\Storelocator\Controller\PickUpInStore\LoggerInterface
     */
    private $logger;
    /**
     * @var \Magento\Rma\Model\Rma\Status\HistoryFactory
     */
    private $rmaStatusHistoryFactory;


    /**
     * @param Context $context
     * @param JsonFactory $resultJsonFactory
     * @param Data $helper
     * @param HistoryFactory $rmaStatusHistoryFactory
     * @param DateTime $date
     * @param ResourceConnection $resourceConnection
     * @param LoggerInterface $logger
     * @param StoreManagerInterface $storeManager
     */
    public function __construct(
        Context $context,
        JsonFactory $resultJsonFactory,
        Data $helper,
        RmaFactory $rmaFactory,
        HistoryFactory $rmaStatusHistoryFactory,
        DateTime $date,
        ResourceConnection $resourceConnection,
        LoggerInterface $logger,
        StoreManagerInterface $storeManager
    ) {
        $this->logger = $logger;
        $this->resultJsonFactory = $resultJsonFactory;
        $this->helper = $helper;
        $this->rmaStatusHistoryFactory = $rmaStatusHistoryFactory;
        $this->date = $date;
        $this->resourceConnection = $resourceConnection;
        $this->storeManager = $storeManager;
        $this->context = $context;
        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() ) {
            if ($this->helper->getUseStandardRmaMailFlow($storeId)) {
                $rma->setReturnToStoreReceivedDate($this->date->gmtDate());
            } else {
                if ($rma->getStatus() === 'pending') {
                    $status = Rma\Source\Status::STATE_AUTHORIZED;
                    $rma->setStatus($status);
                }
            }

            $rma->save();
            $resultJson = $this->resultJsonFactory->create();
            $resultJson->setData(
                [
                    'message' => __('You confirmed that the package ') . $rma->getData('increment_id') . __(
                            ' was accepted.'
                        )
                ]
            );

            $this->updateRma($rma);

            if (!$this->helper->getUseStandardRmaMailFlow($storeId)) {
                $statusHistory = $this->rmaStatusHistoryFactory->create();
                $statusHistory->setRmaEntityId($rma->getEntityId());
                if ($rma->getIsSendAuthEmail()) {
                    $statusHistory->sendAuthorizeEmail();
                }
                if ($rma->getStatus() !== $rma->getOrigData('status')) {
                    $systemHistory = $this->rmaStatusHistoryFactory->create();
                    $systemHistory->setRmaEntityId($rma->getId());
                    $systemHistory->saveSystemComment();
                }
            }

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

            return $resultJson;
        }

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

    /**
     * @param Rma |\Magento\Rma\Api\Data\RmaInterface $rma
     * @return void
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function updateRma($rma)
    {
        $storeId = $this->storeManager->getStore()->getId();
        /* Send mail to store and to customer if not using standard rma mail flow */
        if ($this->helper->getReturnToStoreEnabled($storeId)) {
            if ((int)$rma->getData('return_to_store_id') > 0 && $rma->getStatus() == 'authorized') {
                try {
                    if ($rma->getData('return_to_store_received_date') == null) {
                        if ($rma->getOrigData('status') === 'pending') {
                            $this->helper->sendRmaMail($rma);

                            $sendAuthEmail = false;

                            if ($this->_request->getParam('hash')) {
                                $sendAuthEmail = true;
                            }

                            $rma->setIsSendAuthEmail($sendAuthEmail);
                        }
                    }
                } catch (Exception $exception) {
                    $this->logger->error($exception->getMessage(), ['exception' => $exception]);
                }
            }
        }

        $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) {
                $approvedReturned = '';

                if ($this->helper->getUseStandardRmaMailFlow($storeId)) {
                    $approvedReturned = ', qty_approved = ' . $qty_request . ', qty_returned = ' . $qty_request;

                    $sql = 'UPDATE ' . $tableName . " SET status = '" . Rma\Source\Status::STATE_RECEIVED . "', 
                qty_authorized = " . $qty_request . $approvedReturned . ' WHERE entity_id = ' . $item_id;
                } else {
                    if ($rma->getOrigData('status') === 'authorized' && $rma->getStatus() === 'received') {
                        $approvedReturned = ', qty_approved = ' . $qty_request . ', qty_returned = ' . $qty_request;
                    }

                    $sql = 'UPDATE ' . $tableName . " SET status = '" . Rma\Source\Status::STATE_AUTHORIZED . "', 
                qty_authorized = " . $qty_request . $approvedReturned . ' WHERE entity_id = ' . $item_id;
                }


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

        $comment = 'Return In Store - The package was picked up by store';
        $rmaHistory = $this->rmaStatusHistoryFactory->create();
        $rmaHistory->setRmaEntityId($rma->getId());
        $rmaHistory->setComment($comment);
        $rmaHistory->saveComment($comment, false, true);
    }
}
