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

namespace PortalPeople\ShippingFields\Plugin;

use Magento\Quote\Api\Data\CartInterface;
use Magento\Quote\Model\QuoteRepository;
use Psr\Log\LoggerInterface;

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

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

    /**
     * Before save quote
     *
     * @param QuoteRepository $subject
     * @param CartInterface $quote
     * @return array
     */
    public function beforeSave(QuoteRepository $subject, CartInterface $quote)
    {
        $extensionAttributes = $quote->getExtensionAttributes();
        if ($extensionAttributes) {
            $shippingDate = $extensionAttributes->getShippingDate();
            $shippingMessage = $extensionAttributes->getShippingMessage();
            
            if ($shippingDate !== null) {
                $quote->setData('shipping_date', $shippingDate);
                $this->logger->info('🚢 Quote Plugin: Setting shipping date: ' . $shippingDate);
            }
            
            if ($shippingMessage !== null) {
                $quote->setData('shipping_message', $shippingMessage);
                $this->logger->info('📝 Quote Plugin: Setting shipping message: ' . $shippingMessage);
            }
        }
        
        return [$quote];
    }

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

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