<?php
namespace PortalPeople\ShippingFields\Block\Adminhtml\Order\Edit;

use Magento\Backend\Block\Template;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\Registry;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Backend\Model\Session\Quote as SessionQuote;

class ShippingFields extends Template
{
    protected $coreRegistry;
    protected $orderRepository;
    protected $sessionQuote;

    public function __construct(
        Context $context,
        Registry $registry,
        OrderRepositoryInterface $orderRepository,
        SessionQuote $sessionQuote,
        array $data = []
    ) {
        $this->coreRegistry = $registry;
        $this->orderRepository = $orderRepository;
        $this->sessionQuote = $sessionQuote;
        parent::__construct($context, $data);
    }

    public function getOrder()
    {
        // Try registry first
        $order = $this->coreRegistry->registry('current_order');
        
        // Try session quote (for order edit)
        if (!$order) {
            $orderId = $this->sessionQuote->getOrderId();
            if ($orderId) {
                try {
                    $order = $this->orderRepository->get($orderId);
                } catch (\Exception $e) {
                    // Fall through
                }
            }
        }
        
        // Try request parameter
        if (!$order) {
            $orderId = $this->getRequest()->getParam('order_id');
            if ($orderId) {
                try {
                    $order = $this->orderRepository->get($orderId);
                } catch (\Exception $e) {
                    return null;
                }
            }
        }
        
        return $order;
    }

    public function getShippingDate()
    {
        $order = $this->getOrder();
        return $order ? $order->getData('shipping_date') : '';
    }

    public function getShippingMessage()
    {
        $order = $this->getOrder();
        return $order ? $order->getData('shipping_message') : '';
    }

    public function getUpdateUrl()
    {
        $order = $this->getOrder();
        if (!$order) {
            return '';
        }
        return $this->getUrl('shippingfields/order/update', ['order_id' => $order->getId()]);
    }
}
