<?php

namespace PortalPeople\OrderWebhook\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use PortalPeople\OrderWebhook\Model\WebhookSender;
use Psr\Log\LoggerInterface;

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

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

    /**
     * @param WebhookSender $webhookSender
     * @param LoggerInterface $logger
     */
    public function __construct(
        WebhookSender $webhookSender,
        LoggerInterface $logger
    ) {
        $this->webhookSender = $webhookSender;
        $this->logger = $logger;
    }

    /**
     * Execute observer
     *
     * @param Observer $observer
     * @return void
     */
    public function execute(Observer $observer)
    {
        try {
            /** @var \Magento\Sales\Model\Order $order */
            $order = $observer->getEvent()->getOrder();
            
            if ($order && $order->getId()) {
                // Only send webhook if order status changed to specific states
                $statusesToTrigger = ['pending', 'processing']; //['processing', 'complete', 'shipped'];
                
                if (in_array($order->getStatus(), $statusesToTrigger)) {
                    $this->logger->info('OrderSaveAfter observer triggered for order: ' . $order->getIncrementId());
                    $this->webhookSender->sendOrderData($order, 'order_updated');
                }
            }
        } catch (\Exception $e) {
            $this->logger->error('Error in OrderSaveAfter observer: ' . $e->getMessage());
        }
    }
}
