<?php

namespace Sts\SmartRoute\Controller\Payment;

use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\App\CsrfAwareActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\Request\InvalidRequestException;
class PaymentComplete extends \Magento\Framework\App\Action\Action implements CsrfAwareActionInterface {

    /**
     * Customer session model
     *
     * @var \Magento\Customer\Model\Session
     */
    protected $_customerSession;
    protected $resultPageFactory;
    protected $checkoutSession;
    protected $orderRepository;

    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Customer\Model\Session $customerSession
     */
    public function __construct(
    \Magento\Framework\App\Action\Context $context, \Magento\Customer\Model\Session $customerSession, \Magento\Sales\Api\OrderRepositoryInterface $orderRepository, \Magento\Checkout\Model\Session $checkoutSession
    ) {
        $this->_customerSession = $customerSession;
        $this->checkoutSession = $checkoutSession;
        $this->orderRepository = $orderRepository;
        parent::__construct($context);
    }

    public function execute() {
        /*@var $order \Magento\Sales\Model\Order */
        $order = null;
        if ($this->checkoutSession->getLastOrderId()) {
            $order = $this->orderRepository->get($this->checkoutSession->getLastOrderId());
        }

        $statusCode = $this->getRequest()->getParam('statusCode', '');
        $statusDescription = $this->getRequest()->getParam('statusDesc', '');
        $transactionId = $this->getRequest()->getParam('TransactionId', null);

        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $getLocale = $objectManager->get('Magento\Framework\Locale\Resolver');
        $haystack  = $getLocale->getLocale(); 
        $lang = strstr($haystack, '_', true); 

        $viewData = [
            'OrderId' => $order?$order->getIncrementId():'',
            'OrderStatus' => $order?$order->getStatus():'',
            'TransactionId' => !empty($transactionId)?$transactionId:($order?$order->getPayment()->getLastTransId():''),
            'Status' => $statusCode,            
            'StatusDescription' => __($statusDescription),
            'lang' => $lang,
        ];
        
        //$this->messageManager->addSuccessMessage($statusDescription);
        
        $pageResult = $this->resultFactory->create(ResultFactory::TYPE_PAGE);        
        $pageResult->addHandle('smartroute_payment_paymentcomplete');        
        $pageResult->getLayout()->getBlock('smartroute_payment_success_block')->setData($viewData);
        return $pageResult;
    }
    
    public function createCsrfValidationException(RequestInterface $request): ?InvalidRequestException
    {
        return null;
    }

    public function validateForCsrf(RequestInterface $request): ?bool
    {
        return true;
    }

}
