<?php
declare(strict_types=1);

namespace Autogedal\Extend\Controller\Payment;

use Magento\Framework\App\ResponseInterface;
use Magento\Sales\Model\Order;

class Success extends \Netopia\Netcard\Controller\Payment\Success
{
    /**
     * Execute action based on request and return result
     *
     * @return \Magento\Framework\Controller\ResultInterface|ResponseInterface
     * @throws \Magento\Framework\Exception\NotFoundException
     */
    public function execute()
    {
        $resultPage = $this->resultPageFactory->create();

        /**
         * Get real Order ID
         */
        $orderId = $this->getRealOrderId($this->_request->getParam('orderId'));

        $order = $this->_orderFactory->load($orderId);

        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $customerSession = $objectManager->get('Magento\Customer\Model\Session');
        if ($customerSession->isLoggedIn()) {
            if ($customerSession->getCustomer()->getEmail() != $order->getCustomerEmail()) {
                $msg = _('Eroare, accesul nu este permis');
                $this->messageManager->addError($msg);
                return $this->resultRedirectFactory->create()->setPath('checkout/cart');
            }

            if (!$order || ($order->getStatus() == NULL)) {
                return $this->resultRedirectFactory->create()->setPath('checkout/cart');
            } else {
                if ($order->getStatus() === 'custom_neplatit') {
                    $msg = 'Comanda nu este platita ';
                    $msg .= " | " . current($order->getAllStatusHistory())->getComment();
                    $this->messageManager->addError($msg);
                    /**
                     * Reload cart
                     */
                    $_checkoutSession = $objectManager->create('\Magento\Checkout\Model\Session');
                    $_quoteFactory = $objectManager->create('\Magento\Quote\Model\QuoteFactory');

                    $quote = $_quoteFactory->create()->loadByIdWithoutStore($order->getQuoteId());
                    if ($quote->getId()) {
                        $quote->setIsActive(true)->setReservedOrderId(null)->save();
                        $_checkoutSession->replaceQuote($quote);
                        $_checkoutSession->setQuoteId($quote->getId());
                    }

                    return $this->resultRedirectFactory->create()->setPath('checkout/cart');
                } elseif ($order->getStatus() == Order::STATE_CANCELED || $order->getStatus() == Order::STATE_PAYMENT_REVIEW) {
                    // $msg = current($order->getAllStatusHistory())->getComment();
                    // $this->messageManager->addError($msg);
                    // return $this->resultRedirectFactory->create()->setPath('checkout/cart');
                }
            }

        } else {
            /**
             * If simply want to redirect Guest user to checkout/onepage/success
             * As is defulte in Magento
             */
            // return $this->resultRedirectFactory->create()->setPath('checkout/onepage/success');

            /**
             * Netopia Custom page for Guest
             */
            $cryptedMail = md5($order->getCustomerEmail());
            return $this->resultRedirectFactory->create()->setPath('netopia/payment/guest?&code=' . $cryptedMail . '&orderId=' . $order->getEntityId());
        }


        if (!$order->getEmailSent()) {
            $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $emailSender = $objectManager->create('\Magento\Sales\Model\Order\Email\Sender\OrderSender');
            $emailSender->send($order);
        }

        $this->_eventManager->dispatch(
            'checkout_onepage_controller_success_action',
            ['order_ids' => [$orderId]]
        );
        return $resultPage;
    }
}
