<?php
/**
 * Copyright © Simplyin. All rights reserved.
 */
declare(strict_types=1);

namespace Simplyin\Payment\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Simplyin\Payment\Model\OrderSyncFactory;
use Simplyin\Payment\Model\ResourceModel\OrderSync as OrderSyncResource;
use Simplyin\Payment\Model\ResourceModel\OrderSync\CollectionFactory as OrderSyncCollectionFactory;
use Psr\Log\LoggerInterface;

/**
 * Save SimplyIN order data observer
 *
 * Saves SimplyIN order ID and creates sync entry when order is placed
 */
class CreateSimplyinAccountOnOrder implements ObserverInterface
{
    /**
     * @var OrderRepositoryInterface
     */
    protected $orderRepository;

    /**
     * @var OrderSyncFactory
     */
    protected $orderSyncFactory;

    /**
     * @var OrderSyncResource
     */
    protected $orderSyncResource;

    /**
     * @var OrderSyncCollectionFactory
     */
    protected $orderSyncCollectionFactory;

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

    /**
     * Constructor
     *
     * @param OrderRepositoryInterface $orderRepository
     * @param OrderSyncFactory $orderSyncFactory
     * @param OrderSyncResource $orderSyncResource
     * @param OrderSyncCollectionFactory $orderSyncCollectionFactory
     * @param LoggerInterface $logger
     */
    public function __construct(
        OrderRepositoryInterface $orderRepository,
        OrderSyncFactory $orderSyncFactory,
        OrderSyncResource $orderSyncResource,
        OrderSyncCollectionFactory $orderSyncCollectionFactory,
        LoggerInterface $logger
    ) {
        $this->orderRepository = $orderRepository;
        $this->orderSyncFactory = $orderSyncFactory;
        $this->orderSyncResource = $orderSyncResource;
        $this->orderSyncCollectionFactory = $orderSyncCollectionFactory;
        $this->logger = $logger;
    }

    /**
     * Execute observer
     *
     * Saves SimplyIN order ID to order table and creates sync entry
     *
     * @param Observer $observer
     * @return void
     */
    public function execute(Observer $observer): void
    {
        try {
            /** @var \Magento\Sales\Model\Order $order */
            $order = $observer->getEvent()->getOrder();

            if (!$order || !$order->getId()) {
                return;
            }

            // Check if this is a SimplyIN payment
            $payment = $order->getPayment();
            if (!$payment || $payment->getMethod() !== 'simplyin_payment') {
                return;
            }

            // Get SimplyIN order ID from payment additional information
            $simplyinOrderId = $payment->getAdditionalInformation('simplyin_order_id');

            if (!$simplyinOrderId) {
                $this->logger->info('SimplyIN Observer: No SimplyIN order ID found for order #' . $order->getIncrementId());
                return;
            }

            $this->logger->info('SimplyIN Observer: Processing order #' . $order->getIncrementId());

            // Store SimplyIN order ID only in simplyin_order_sync table (not in sales_order)
            $now = (new \DateTime())->format('Y-m-d H:i:s');

            // Check if entry already exists in simplyin_order_sync table
            $collection = $this->orderSyncCollectionFactory->create();
            $collection->addFieldToFilter('order_id', (int)$order->getId());
            $existingRecord = $collection->getFirstItem();

            if ($existingRecord && $existingRecord->getId()) {
                $existingRecord->setSimplyinOrderId($simplyinOrderId);
                $existingRecord->setSyncStatus('synced');
                $existingRecord->setLastSyncAt($now);
                $this->orderSyncResource->save($existingRecord);

                $this->logger->info('SimplyIN Observer: Updated existing order sync entry', [
                    'magento_order_id' => $order->getId(),
                    'simplyin_order_id' => $simplyinOrderId
                ]);
            } else {
                $orderSync = $this->orderSyncFactory->create();
                $orderSync->setOrderId((int)$order->getId());
                $orderSync->setSimplyinOrderId($simplyinOrderId);
                $orderSync->setSyncStatus('synced');
                $orderSync->setLastSyncAt($now);
                $this->orderSyncResource->save($orderSync);

                $this->logger->info('SimplyIN Observer: Created order sync entry', [
                    'magento_order_id' => $order->getId(),
                    'simplyin_order_id' => $simplyinOrderId
                ]);
            }

        } catch (\Exception $e) {
            $this->logger->error('SimplyIN Observer Error: ' . $e->getMessage(), [
                'trace' => $e->getTraceAsString()
            ]);
        }
    }
}
