<?php

namespace Benhauer\Salesmanago\Observer\Events\Purchase;

use \Psr\Log\LoggerInterface;

use \Magento\Framework\Stdlib\DateTime\TimezoneInterface as MagentoDateTime;
use \Magento\Checkout\Model\Session;
use \Magento\Store\Api\Data\StoreInterface;
use \Magento\Newsletter\Model\Subscriber;
use \Magento\Sales\Api\OrderRepositoryInterface;
use \Magento\Quote\Model\QuoteFactory;
use \Magento\Framework\Stdlib\CookieManagerInterface;
use \Magento\Customer\Api\CustomerRepositoryInterface;
use \Magento\Framework\Event\Observer;
use \Magento\Store\Model\StoreManagerInterface;

use \SALESmanago\Factories\FactoryOrganizer;
use \SALESmanago\Provider\UserProvider;
use \SALESmanago\Services\ConnectSalesManagoService;

use \Benhauer\Salesmanago\Observer\AbstractObserver;
use \Benhauer\Salesmanago\Model\Hooks as HooksModel;
use \Benhauer\Salesmanago\Model\Contact;
use \Benhauer\Salesmanago\Helper\Tagger;
use \Benhauer\Salesmanago\Helper\Config as SmPluginConfig;

use Benhauer\Salesmanago\Observer\AbstractObserver as SalesmanagoAbstractObserver;

class OrderStatusChanged extends SalesmanagoAbstractObserver
{
    public $orderRepository;
    public $quoteFactory;
    public $cookieManager;

    public function __construct(
        Session $session,
        StoreInterface $store,
        Subscriber $subscriber,
        HooksModel $model,
        CustomerRepositoryInterface $customerRepositoryInterface,
        CookieManagerInterface $cookieManager,
        MagentoDateTime $objDate,
        FactoryOrganizer $factoryOrganizer,
        Tagger $tagger,
        LoggerInterface $logger,
        Contact $modelContact,
        StoreManagerInterface $storeManager,
        QuoteFactory $quoteFactory
    ) {
        parent::__construct(
            $session,
            $store,
            $subscriber,
            $model,
            $customerRepositoryInterface,
            $cookieManager,
            $objDate,
            $factoryOrganizer,
            $tagger,
            $logger,
            $modelContact,
            $storeManager
        );
        $this->quoteFactory = $quoteFactory;
    }

    public function hookAct(Observer $observer)
    {
        $order = $observer->getOrder();
        $orderStatus = $order->getStatus();

        //Runs for special order types
        if ($type = $this->model->checkOrderStatusToProcess($orderStatus)) {
            $this->sendExternalEventFromOrder($order, false, $type);
        }

        if (!SmPluginConfig::$enOrderTypes) {
            return true;
        }

        $orderTypes = $this->model->getSubmittedOrderTypes();

        // Only trigger when an order enters processing state.
        if ($this->model->checkIfOrderStatusChoosed($orderStatus)) {
            $this->sendExternalEventFromOrder($order);
            return true;
        }

        return false;
    }

    public function sendExternalEventFromOrder($order, $withUpsert = true, $eventType = 'OTHER')
    {
        try {
            $contact = '';

            $billingAddress = $order->getBillingAddress();
            $customerEmail = $billingAddress->getEmail();

            $connectSalesManago = $this->getConnectSalesManago();

            if ($order->getCustomerId() == null && $order->getCustomerIsGuest()) {
                $Contact = $this->modelContact->getContactByCustomerBillingAddress($billingAddress, $customerEmail);
                $Contact->getOptions()->setAdditional(
                    [HooksModel::SYNC_RULE => $this->model->getSynchronizeRule()]
                );

                $contact = $Contact->getDataOptions();

                if ($withUpsert) {
                    $contact = $this->tagger
                        ->setModel($this->model)
                        ->setTags($contact, [Tagger::T_PURCHASE, Tagger::T_GUEST_PURCHASE]);

                    $response = $this->upsertContact($contact, $connectSalesManago, SalesmanagoAbstractObserver::UPSERT_FLAG_ALL_DATA);
                }
            } elseif ($order->getCustomerId() != null) {
                $Contact = $this->modelContact->getContactByCustomerId($order->getCustomerId());
                $contact = $Contact->getDataOptions();

                if ($withUpsert) {
                    $contact = $this->tagger
                        ->setModel($this->model)
                        ->setTags($contact, Tagger::T_PURCHASE);

                    $response = $this->upsertContact($contact, $connectSalesManago, SalesmanagoAbstractObserver::UPSERT_FLAG_ALL_DATA);
                }

                $contact = $contact['data'];
            }

            if (isset($contact['data'])) {
                $contact = $contact['data'];
            }

            if (!isset($contact['email']) || empty($contact['email'])) {
                return true;
            }

            $products = $this->getProductsFromOrder($order, $this->quoteFactory);

            $products['description'] = ($eventType == 'OTHER')
                ? $order->getState()
                : $products['description'];

            $response = $connectSalesManago->contactExtEvent(
                $eventType,
                $products,
                $contact,
                ''
            );

            $this->deleteEventCookie($response);
        } catch (\Exception $e) {
            $this->logger->critical($e->getMessage());
        }
    }
}
