<?php
namespace PortalPeople\ShippingFields\Model;

use PortalPeople\ShippingFields\Api\ShippingFieldsInterface;
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;

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

    public function saveShippingFields($shippingDate, $shippingMessage)
    {
        try {
            $quote = $this->checkoutSession->getQuote();
            
            if ($quote && $quote->getId()) {
                if ($shippingDate) {
                    $quote->setData('shipping_date', $shippingDate);
                    $this->logger->info('API: Set shipping_date: ' . $shippingDate);
                }
                
                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;
        }
    }
}
