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

use Magento\Backend\Block\Template;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\Registry;

class ShippingFields extends Template
{
    protected $coreRegistry;

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

    public function getOrder()
    {
        return $this->coreRegistry->registry('current_order');
    }

    public function getShippingDate()
    {
        $order = $this->getOrder();
        $date = $order ? $order->getData('shipping_date') : null;
        
        if ($date) {
            try {
                $dateTime = new \DateTime($date);
                return $dateTime->format('d/m/Y');
            } catch (\Exception $e) {
                return $date;
            }
        }
        
        return null;
    }

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

    public function hasShippingFields()
    {
        return $this->getShippingDate() || $this->getShippingMessage();
    }

    /**
     * Raw date in Y-m-d for the date input
     */
    public function getRawShippingDate(): string
    {
        $order = $this->getOrder();
        $date = $order ? $order->getData('shipping_date') : null;
        if (!$date) {
            return '';
        }
        try {
            return (new \DateTime($date))->format('Y-m-d');
        } catch (\Exception $e) {
            return $date;
        }
    }

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