<?php

namespace Benhauer\Salesmanago\Observer;

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\Model\Hooks as HooksModel;
use \Benhauer\Salesmanago\Model\Contact;
use \Benhauer\Salesmanago\Helper\Tagger;

use Benhauer\Salesmanago\Observer\AbstractObserver as SalesmanagoAbstractObserver;

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

    const PAYMENT_METHOD = 'klarna';

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

    public function hookAct(Observer $observer)
    {
        try {
            $order = $observer->getEvent()->getOrder();
            $paymentMethod = $order->getPayment()->getMethod();

            if (strpos($paymentMethod, self::PAYMENT_METHOD) === false) {
                return true;
            }

            $contact = '';

            $billingAddress = $order->getBillingAddress();
            $customerEmail = $billingAddress->getEmail();
            $smClientCookie = $this->cookieManager->getCookie('smclient');

            $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();

                $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);

                /*$response = $connectSalesManago->contactUpsert(
                    $contact['data'],
                    $contact['options'],
                    ''
                );

                $this->createContactCookie($response);

                $this->synchronizeContactFromSm(
                    $Contact->getEmail(),
                    $response
                );*/
            } elseif ($order->getCustomerId() != null) {
                $customerId = $order->getCustomerId();
                $contact = $this->getCustomerById($customerId);

                $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'];
            } elseif ($smClientCookie != null && !isset($contact['email'])) {
                $contact = [
                    'contactId' => $smClientCookie
                ];
            }

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

            $response = $connectSalesManago->contactExtEvent(
                ConnectSalesManagoService::EVENT_TYPE_PURCHASE,
                $products,
                $contact,
                ''
            );

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