<?php
/**
 * Shipping Information Management Plugin for Shipping Fields
 */

namespace PortalPeople\ShippingFields\Plugin;

use Magento\Checkout\Model\ShippingInformationManagement;
use Magento\Checkout\Api\Data\ShippingInformationInterface;
use Magento\Quote\Api\CartRepositoryInterface;
use Psr\Log\LoggerInterface;

class ShippingInformationManagementPlugin
{
    /**
     * @var CartRepositoryInterface
     */
    private $cartRepository;

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

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

    /**
     * Before save address information
     *
     * @param ShippingInformationManagement $subject
     * @param int $cartId
     * @param ShippingInformationInterface $addressInformation
     * @return array
     */
    public function beforeSaveAddressInformation(
        ShippingInformationManagement $subject,
        $cartId,
        ShippingInformationInterface $addressInformation
    ) {
        $this->logger->info('🚢 SHIPPING PLUGIN: Processing cart ID: ' . $cartId);
        
        $shippingDate = null;
        $deliveryMessage = null;
        
        // Method 1: Try to get from extension attributes
        $extensionAttributes = $addressInformation->getExtensionAttributes();
        
        if ($extensionAttributes) {
            $this->logger->info('🚢 Extension attributes found');
            
            if (method_exists($extensionAttributes, 'getShippingDate')) {
                $shippingDate = $extensionAttributes->getShippingDate();
                $this->logger->info('📅 Extension shipping_date: ' . ($shippingDate ?: 'null'));
            }
            
            if (method_exists($extensionAttributes, 'getDeliveryMessage')) {
                $deliveryMessage = $extensionAttributes->getDeliveryMessage();
                $this->logger->info('📝 Extension delivery_message: ' . ($deliveryMessage ?: 'null'));
            }
        } else {
            $this->logger->info('⚠️ No extension attributes found');
        }
        
        // Method 2: Fallback - try to get from request JSON
        if (!$shippingDate && !$deliveryMessage) {
            $this->logger->info('🔍 Trying to get data from request');
            
            try {
                $request = $this->getRequest();
                if ($request) {
                    $content = $request->getContent();
                    $this->logger->info('📦 Request content length: ' . strlen($content));
                    
                    if ($content) {
                        $data = json_decode($content, true);
                        
                        if (isset($data['addressInformation']['extension_attributes']['shipping_date'])) {
                            $shippingDate = $data['addressInformation']['extension_attributes']['shipping_date'];
                            $this->logger->info('📅 Request shipping_date: ' . $shippingDate);
                        }
                        
                        if (isset($data['addressInformation']['extension_attributes']['delivery_message'])) {

                        if (isset($data['addressInformation']['extension_attributes']['shipping_message'])) {
                            $deliveryMessage = $data['addressInformation']['extension_attributes']['shipping_message'];
                            $this->logger->info('📝 Request shipping_message: ' . $deliveryMessage);
                        }
                            $deliveryMessage = $data['addressInformation']['extension_attributes']['delivery_message'];

                        if (isset($data['addressInformation']['extension_attributes']['shipping_message'])) {
                            $deliveryMessage = $data['addressInformation']['extension_attributes']['shipping_message'];
                            $this->logger->info('📝 Request shipping_message: ' . $deliveryMessage);
                        }
                            $this->logger->info('📝 Request delivery_message: ' . $deliveryMessage);
                        }
                        
                        // Log full structure for debugging
                        $this->logger->info('📋 Full request data: ' . json_encode($data));
                    }
                }
            } catch (\Exception $e) {
                $this->logger->error('❌ Error reading request: ' . $e->getMessage());
            }
        }
        
        // Save to quote if we have data
        if ($shippingDate || $deliveryMessage) {
            try {
                $quote = $this->cartRepository->get($cartId);
                
                if ($shippingDate) {
                    $quote->setData('shipping_date', $shippingDate);
                    $this->logger->info('✅ Set shipping_date on quote: ' . $shippingDate);
                }
                
                if ($deliveryMessage) {
                    $quote->setData('shipping_message', $deliveryMessage);
                    $this->logger->info('✅ Set shipping_message on quote: ' . $deliveryMessage);
                }
                
                $this->cartRepository->save($quote);
                $this->logger->info('💾 Saved shipping fields to quote ID: ' . $quote->getId());
                
            } catch (\Exception $e) {
                $this->logger->error('❌ Shipping Plugin Error: ' . $e->getMessage());
                $this->logger->error('❌ Stack trace: ' . $e->getTraceAsString());
            }
        } else {
            $this->logger->info('⚠️ No shipping data found to save');
        }
        
        return [$cartId, $addressInformation];
    }
    
    /**
     * Get request object
     *
     * @return \Magento\Framework\App\RequestInterface|null
     */
    private function getRequest()
    {
        try {
            $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            return $objectManager->get(\Magento\Framework\App\RequestInterface::class);
        } catch (\Exception $e) {
            $this->logger->error('Could not get request: ' . $e->getMessage());
            return null;
        }
    }
}
