<?php
/**
 * Order Repository Plugin for Shipping Fields
 */

namespace PortalPeople\ShippingFields\Plugin;

use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Model\OrderRepository;
use Psr\Log\LoggerInterface;

class OrderRepositoryPlugin
{
    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @var \Magento\Framework\App\RequestInterface
     */
    private $request;

    /**
     * Constructor
     *
     * @param LoggerInterface $logger
     * @param \Magento\Framework\App\RequestInterface $request
     */
    public function __construct(
        LoggerInterface $logger,
        \Magento\Framework\App\RequestInterface $request
    ) {
        $this->logger = $logger;
        $this->request = $request;
    }

    /**
     * Before save order
     *
     * @param OrderRepository $subject
     * @param OrderInterface $order
     * @return array
     */
    public function beforeSave(OrderRepository $subject, OrderInterface $order)
    {
        // Try to get data from request first (for order edit page)
        $orderData = $this->request->getParam('order');
        
        if (is_array($orderData)) {
            if (isset($orderData['shipping_date']) && $orderData['shipping_date'] !== '') {
                $order->setData('shipping_date', $orderData['shipping_date']);
                $this->logger->info('🚢 Order Plugin (from request): Setting shipping date: ' . $orderData['shipping_date']);
            }
            
            if (isset($orderData['shipping_message']) && $orderData['shipping_message'] !== '') {
                $order->setData('shipping_message', $orderData['shipping_message']);
                $this->logger->info('📝 Order Plugin (from request): Setting shipping message: ' . $orderData['shipping_message']);
            }
        }
        
        // Also check extension attributes (for API/other sources)
        $extensionAttributes = $order->getExtensionAttributes();
        if ($extensionAttributes) {
            $shippingDate = $extensionAttributes->getShippingDate();
            $shippingMessage = $extensionAttributes->getShippingMessage();
            
            if ($shippingDate !== null) {
                $order->setData('shipping_date', $shippingDate);
                $this->logger->info('🚢 Order Plugin (from extension): Setting shipping date: ' . $shippingDate);
            }
            
            if ($shippingMessage !== null) {
                $order->setData('shipping_message', $shippingMessage);
                $this->logger->info('📝 Order Plugin (from extension): Setting shipping message: ' . $shippingMessage);
            }
        }
        
        return [$order];
    }

    /**
     * After get order
     *
     * @param OrderRepository $subject
     * @param OrderInterface $order
     * @return OrderInterface
     */
    public function afterGet(OrderRepository $subject, OrderInterface $order)
    {
        $extensionAttributes = $order->getExtensionAttributes();
        
        if ($extensionAttributes === null) {
            $extensionAttributes = $this->getExtensionAttributesFactory()->create();
        }
        
        $shippingDate = $order->getData('shipping_date');
        $shippingMessage = $order->getData('shipping_message');
        
        if ($shippingDate !== null) {
            $extensionAttributes->setShippingDate($shippingDate);
        }
        
        if ($shippingMessage !== null) {
            $extensionAttributes->setShippingMessage($shippingMessage);
        }
        
        $order->setExtensionAttributes($extensionAttributes);
        
        return $order;
    }

    /**
     * Get extension attributes factory
     *
     * @return \Magento\Sales\Api\Data\OrderExtensionFactory
     */
    private function getExtensionAttributesFactory()
    {
        return \Magento\Framework\App\ObjectManager::getInstance()
            ->get(\Magento\Sales\Api\Data\OrderExtensionFactory::class);
    }
}
