<?php
namespace PortalPeople\ShippingFields\Model;

use PortalPeople\ShippingFields\Api\ShippingFieldsInterface;
use PortalPeople\ShippingFields\Model\ShippingDateFormatter;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Checkout\Model\Session as CheckoutSession;
use Psr\Log\LoggerInterface;

class ShippingFieldsManagement implements ShippingFieldsInterface
{
    protected $cartRepository;
    protected $checkoutSession;
    protected $logger;
    protected $shippingDateFormatter;

    public function __construct(
        CartRepositoryInterface $cartRepository,
        CheckoutSession $checkoutSession,
        LoggerInterface $logger,
        ShippingDateFormatter $shippingDateFormatter
    ) {
        $this->cartRepository = $cartRepository;
        $this->checkoutSession = $checkoutSession;
        $this->logger = $logger;
        $this->shippingDateFormatter = $shippingDateFormatter;
    }

    public function saveShippingFields($shippingDate, $shippingMessage, $shippingW3w = null)
    {
        try {
            $quote = $this->checkoutSession->getQuote();
            $normalizedShippingDate = $this->shippingDateFormatter->normalizeForStorage($shippingDate);
            
            if ($quote && $quote->getId()) {
                if ($normalizedShippingDate !== null) {
                    $quote->setData('shipping_date', $normalizedShippingDate);
                    $this->logger->info('API: Set shipping_date: ' . $normalizedShippingDate);
                }

                if ($shippingW3w) {
                    $quote->setData('shipping_w3w', $shippingW3w);
                    $this->logger->info('API: Set shipping_w3w');
                }
                
                if ($shippingMessage) {
                    $quote->setData('shipping_message', $shippingMessage);
                    $this->logger->info('API: Set shipping_message: ' . $shippingMessage);
                }
                
                $this->cartRepository->save($quote);
                $this->logger->info('API: Saved shipping fields to quote ID: ' . $quote->getId());
                
                return true;
            }
            
            return false;
        } catch (\Exception $e) {
            $this->logger->error('API Error saving shipping fields: ' . $e->getMessage());
            return false;
        }
    }
}
