<?php

namespace PortalPeople\OrderWebhook\Observer;

use Magento\Framework\App\Area;
use Magento\Framework\App\State;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use PortalPeople\OrderWebhook\Model\WebhookSender;
use Psr\Log\LoggerInterface;

/**
 * Observer for order place after event
 */
class OrderPlaceAfter implements ObserverInterface
{
    /**
     * @var WebhookSender
     */
    private $webhookSender;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var State
     */
    private $appState;

    /**
     * @param WebhookSender $webhookSender
     * @param LoggerInterface $logger
     * @param State|null $appState
     */
    public function __construct(
        WebhookSender $webhookSender,
        LoggerInterface $logger,
        State $appState = null
    ) {
        $this->webhookSender = $webhookSender;
        $this->logger = $logger;
        $this->appState = $appState ?: ObjectManager::getInstance()->get(State::class);
    }

    /**
     * Execute observer
     *
     * @param Observer $observer
     * @return void
     */
    public function execute(Observer $observer)
    {
        try {
            /** @var \Magento\Sales\Model\Order $order */
            $order = $observer->getEvent()->getOrder();

            $this->logger->info('[OrderWebhook] OrderPlaceAfter execute invoked');
            
            if ($order && $order->getId()) {
                $this->logger->info('[OrderWebhook] OrderPlaceAfter order=' . $order->getIncrementId() . ' status=' . $order->getStatus());
                // Guard against duplicate automatic sends for the same order.
                if ($order->getData('ngauge_order_id') || $order->getData('ngauge_order_no')) {
                    $this->logger->info('OrderPlaceAfter: skipping already-sent order ' . $order->getIncrementId());
                    return;
                }

                // Admin-created orders are sent from OrderSaveAfter after payment capture.
                if ($this->isAdminArea()) {
                    $this->logger->info('OrderPlaceAfter: skipping admin-area order ' . $order->getIncrementId() . ' - will send on payment');
                    return;
                }
                $this->logger->info('OrderPlaceAfter observer triggered for order: ' . $order->getIncrementId());
                $this->webhookSender->sendOrderData($order, 'order_placed');
            }
        } catch (\Exception $e) {
            $this->logger->error('Error in OrderPlaceAfter observer: ' . $e->getMessage());
        }
    }

    /**
     * Determine if current execution is in admin area.
     *
     * @return bool
     */
    private function isAdminArea(): bool
    {
        try {
            return $this->appState->getAreaCode() === Area::AREA_ADMINHTML;
        } catch (\Exception $e) {
            return false;
        }
    }
}
