<?php

namespace Oney\ThreeByFour\Observer;

use Magento\Payment\Observer\AbstractDataAssignObserver;
use Magento\Sales\Model\Order;
use Oney\ThreeByFour\Api\Payment\CancelInterface;
use Oney\ThreeByFour\Logger\Logger;

/**
 * Cancel Order Observer
 * 
 * Observer triggered when an order is cancelled.
 * Handles cancellation of Oney ThreeByFour payment orders.
 * 
 * @package Oney\ThreeByFour\Observer
 * @version 1.0.0
 * @author Oney
 * @since 1.0.0
 */
class CancelOrder extends AbstractDataAssignObserver
{
    /**
     * Cancel service instance
     * 
     * @var CancelInterface
     * @version 1.0.0
     */
    protected $cancelService;
    
    /**
     * Logger instance
     * 
     * @var Logger
     * @version 1.0.0
     */
    protected $logger;

    /**
     * Constructor
     * 
     * @param CancelInterface $cancelService Cancel service
     * @param Logger $logger Logger instance
     * @version 1.0.0
     */
    public function __construct(
        CancelInterface $cancelService,
        Logger $logger
    ) {
        $this->cancelService = $cancelService;
        $this->logger = $logger;
    }

    /**
     * Execute observer
     * 
     * Handles order cancellation for Oney ThreeByFour payment method.
     * 
     * @param \Magento\Framework\Event\Observer $observer Observer instance
     * @return void
     * @version 1.0.0
     */
    public function execute(\Magento\Framework\Event\Observer $observer): void
    {
        /** @var Order $order */
        $order = $observer->getOrder();
        if(strpos($order->getPayment()->getMethod(), "threebyfour") !== false) {
            $this->logger->info("[INFO] [OBSERVER] CancelOrder triggered: ", [
                'order_id' => $order->getId(),
                'method' => $order->getPayment()->getMethod()
            ]);
            $this->cancelService->cancel($order);
        }
    }
}
