<?php

namespace Leadlion\SalesOrder\Observer;

use Magento\Framework\App\State;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Exception\LocalizedException;
use Leadlion\SalesOrder\Helper\Data;

class SaveOperatorId implements ObserverInterface
{
    protected $state;
    protected $customHelper;

    public function __construct(
        State $state,
        Data $customHelper
    ) {
        $this->state = $state;
        $this->customHelper = $customHelper;
    }

    /**
     * @param Observer $observer
     * @return bool
     * @throws \Exception
     */
    public function execute(Observer $observer)
    {
        try {
            $areaCode = $this->state->getAreaCode();
        } catch (LocalizedException $exception) {
            $areaCode = null;
        }

        $order = $observer->getOrder();

        if ($areaCode === 'adminhtml' && $order->getStatus() == 'pending') {
            $adminUserId = $this->customHelper->getAdminUserId();
            $order->setData('autogedal_operator_id', $adminUserId);
        }
        return true;
    }
}
