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

            $this->logger->info('[OrderWebhook] OrderSaveAfter execute invoked');

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

                // Only send webhook when status moves to processing (payment captured)
                // Frontend order_placed is handled by OrderPlaceAfter; admin orders wait for payment here
                $statusesToTrigger = ['processing'];

                // Skip if the status hasn't actually changed (e.g. initial save after order_place_after)
                $previousStatus = $order->getOrigData('status');
                if ($previousStatus === $order->getStatus()) {
                    return;
                }

                // Extra safety: only send when Magento has recorded payment.
                if (!$this->isOrderPaid($order)) {
                    $this->logger->info('OrderSaveAfter: skipping unpaid order ' . $order->getIncrementId());
                    return;
                }

                if (in_array($order->getStatus(), $statusesToTrigger, true)) {
                    $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());
        }
    }

    /**
     * Determine whether an order has a recorded paid amount.
     *
     * @param object $order
     * @return bool
     */
    private function isOrderPaid($order): bool
    {
        $totalPaid = (float)$order->getTotalPaid();
        $baseTotalPaid = (float)$order->getBaseTotalPaid();

        return $totalPaid > 0.0001 || $baseTotalPaid > 0.0001;
    }
}
