<?php
namespace Autogedal\Extend\Observer\Osc;

use Magento\Framework\Event\Observer;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Downloadable\Model\Product\Type;
use Magento\Customer\Model\AccountManagement;
use Exception;

class QuoteSubmitSuccess extends \Mageplaza\Osc\Observer\QuoteSubmitSuccess
{
    /**
     * @param Observer $observer
     *
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function execute(Observer $observer)
    {
        /**
         * @var \Magento\Quote\Model\Quote $quote
         */
        $quote = $observer->getEvent()->getQuote();
        $order = $observer->getEvent()->getOrder();

        $oscData = $this->checkoutSession->getOscData();
        if (isset($oscData['register']) && $oscData['register']
            && isset($oscData['password'])
            && $oscData['password']
        ) {
            /* Save customer information for order and save address in address book */
            $this->setCustomerInformation($quote, $order)->setSaveInAddressBook($quote);

            if ($this->checkoutSession->getIsCreatedAccountPaypalExpress()) {
                $customer = $quote->getCustomer();
                $this->checkoutSession->unsIsCreatedAccountPaypalExpress();
            } else {
                $email     = $order->getCustomerEmail();
                $websiteId = $this->storeManager->getStore()->getWebsiteId();

                try {
                    $customer = $this->customerRepository->get($email, $websiteId);
                } catch (NoSuchEntityException $e) {
                    $customer = $this->customerManagement->create($order->getId());
                }
            }

            /* Set customer Id for address */
            if ($customer->getId()) {
                $quote->getBillingAddress()->setCustomerId($customer->getId());
                if ($shippingAddress = $quote->getShippingAddress()) {
                    $shippingAddress->setCustomerId($customer->getId());
                }
            }

            if ($customer->getId()
                && $this->accountManagement->getConfirmationStatus($customer->getId()) === AccountManagement::ACCOUNT_CONFIRMATION_REQUIRED
            ) {
                $url = $this->_customerUrl->getEmailConfirmationUrl($customer->getEmail());
                $this->messageManager->addSuccessMessage(
                // @codingStandardsIgnoreStart
                    __(
                        'You must confirm your account. Please check your email for the confirmation link or <a href="%1">click here</a> for a new link.',
                        $url
                    )
                // @codingStandardsIgnoreEnd
                );
            } else {
                $this->_customerSession->loginById($customer->getId());
            }

            $isDownloadable = false;
            foreach ($quote->getAllItems() as $item) {
                if ($item->getProductType() == Type::TYPE_DOWNLOADABLE) {
                    $isDownloadable = true;
                    break;
                }
            }
            if ($isDownloadable) {
                foreach ($order->getAllItems() as $item) {
                    $this->saveDownloadableOrderItem($item, $order);
                }
            }
        }

        if (isset($oscData['is_subscribed']) && $oscData['is_subscribed']) {
            try {
                if (!$this->_customerSession->isLoggedIn()) {
                    $subscribedEmail = $quote->getBillingAddress()->getEmail();
                    $this->subscriberFactory->create()
                        ->subscribe($subscribedEmail);
                } else {
                    $customer = $this->_customerSession->getCustomer();
                    $this->subscriberFactory->create()
                        ->subscribeCustomerById($customer->getId());
                }
            } catch (Exception $e) {
                $this->messageManager->addErrorMessage(__('There is an error while subscribing for newsletter.'));
            }
        }

        $this->checkoutSession->unsOscData();
    }
}
