<?php
namespace PortalPeople\ShippingFields\Controller\Adminhtml\Order;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Sales\Api\OrderRepositoryInterface;
use Psr\Log\LoggerInterface;

class Update extends Action
{
    protected $orderRepository;
    protected $logger;

    public function __construct(
        Context $context,
        OrderRepositoryInterface $orderRepository,
        LoggerInterface $logger
    ) {
        parent::__construct($context);
        $this->orderRepository = $orderRepository;
        $this->logger = $logger;
    }

    public function execute()
    {
        $resultRedirect = $this->resultRedirectFactory->create();
        
        try {
            $orderId = $this->getRequest()->getParam('order_id');
            $shippingDate = $this->getRequest()->getParam('shipping_date');
            $shippingMessage = $this->getRequest()->getParam('shipping_message');

            if (!$orderId) {
                throw new \Exception('Order ID is required');
            }

            $order = $this->orderRepository->get($orderId);
            $order->setData('shipping_date', $shippingDate);
            $order->setData('shipping_message', $shippingMessage);
            $this->orderRepository->save($order);

            $this->messageManager->addSuccessMessage(__('Shipping fields have been updated.'));
            
        } catch (\Exception $e) {
            $this->logger->error('Error updating shipping fields: ' . $e->getMessage());
            $this->messageManager->addErrorMessage(__('Error updating shipping fields: %1', $e->getMessage()));
        }

        return $resultRedirect->setPath('sales/order/view', ['order_id' => $orderId]);
    }

    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('Magento_Sales::actions_edit');
    }
}
