<?php
/**
 * Quote to Order Plugin for Shipping Fields
 */

namespace PortalPeople\ShippingFields\Plugin;

use Magento\Quote\Model\Quote;
use Magento\Sales\Model\Order;
use Psr\Log\LoggerInterface;

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

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

    /**
     * Transfer shipping fields from quote to order
     *
     * @param \Magento\Quote\Model\Quote\Item\ToOrderItem $subject
     * @param \Closure $proceed
     * @param Quote $quote
     * @param array $additional
     * @return Order
     */
    public function aroundConvert(
        \Magento\Quote\Model\Quote\Item\ToOrderItem $subject,
        \Closure $proceed,
        $quote,
        $additional = []
    ) {
        /** @var Order $order */
        $order = $proceed($quote, $additional);
        
        if ($quote instanceof Quote) {
            $shippingDate = $quote->getData('shipping_date');
            $shippingMessage = $quote->getData('shipping_message');
            
            if ($shippingDate) {
                $order->setData('shipping_date', $shippingDate);
                $this->logger->info('[ShippingFields] QuoteToOrder: transferred shipping_date: ' . $shippingDate);
            }
            
            if ($shippingMessage) {
                $order->setData('shipping_message', $shippingMessage);
                $this->logger->info('[ShippingFields] QuoteToOrder: transferred shipping_message');
            }
        }
        
        return $order;
    }
}
