<?php

namespace Benhauer\Salesmanago\Observer\Events\Purchase;

use \Benhauer\Salesmanago\Model\Config\PurchasesConfig;
use \Magento\Framework\Event\Observer;
use \Benhauer\Salesmanago\Observer\Events\Purchase\AbstractPurchaseObserver as SalesmanagoAbstractPurchaseObserver;

class PurchaseObserver extends SalesmanagoAbstractPurchaseObserver
{
    public function hookAct(Observer $observer)
    {
        try {
            $order = $observer->getData('order');
            $orderIds = $observer->getData('order_ids');

            /*this is for specific hooks*/
            if (empty($order) && $orderIds) {
                $orderId = reset($orderIds);
                $order = $this->orderRepository->get($orderId);
            }

            $type = $this->purchasesConfigModel->getType();

            if ($type == PurchasesConfig::P_T_ON_EVENT
                && $observer->getEvent()->getName() == PurchasesConfig::$defaultPurchaseEvent
            ) {
                $this->setOrderIdToCookie($order->getId);
                return true;
            } else if (
                $type == PurchasesConfig::P_T_ON_EVENT
                && $observer->getEvent()->getName() == $this->purchasesConfigModel->getConfig()
            ) {
                $orderId = $this->getOrderIdFromCookie();
                $order = $this->orderRepository->get($orderId);
            } else if ($type != PurchasesConfig::P_T_ON_EVENT
                && $type != PurchasesConfig::P_T_ON_EVENT
                && $type != PurchasesConfig::P_T_ON_CHOOSEN_EVENT
                && $observer->getEvent()->getName() != PurchasesConfig::$defaultPurchaseEvent
            ) {
                return false;
            }

            if (empty($order)) {
                return false;
            }

            return $this->executePurchase($order);
        } catch (\Exception $e) {
            $this->logger->critical($e->getMessage());
        }
    }
}
