<?php


namespace Magetop\Advancepreview\Observer\Frontend;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
//use Magento\Framework\App\Request\DataPersistorInterface;
//use Magento\Framework\App\ObjectManager;
class ObserverforAddCustomVariable  implements ObserverInterface
{
    protected $orderFactory;
    protected $resOrderFactory;
    public function __construct(
        \Magento\Sales\Model\OrderFactory $orderFactory,
        \Magento\Sales\Model\ResourceModel\OrderFactory $resOrderFactory
    )
    {
        $this->orderFactory = $orderFactory;
        $this->resOrderFactory = $resOrderFactory;
    }

    public function execute(Observer $observer)
    {
        // TODO: Implement execute() method.
        $transport = $observer->getTransport();
        $orderId = $transport->getData('order_id');
        if($orderId > 0) {
            $order = $this->getOrderById($orderId);
            if($order && $order->getId()) {
                $transport['custom_order_date'] = date('m/d/Y',strtotime($order->getCreatedAt()));
            }
        }

    }

    /**
     * @param $orderId
     * @return \Magento\Sales\Model\Order
     */
    protected function getOrderById($orderId) {
        $order = $this->orderFactory->create();
        try {
            $this->resOrderFactory->create()->load($order,$orderId);
        }
        catch (\Exception $exception) {

        }
        return $order;
    }
}
