<?php 

namespace Sts\SmartRoute\Controller\Payment; 

use Magento\Quote\Api\CartManagementInterface;
use Magento\Sales\Model\Order;
use Magento\Framework\Controller\ResultFactory;

class Redirect extends \Magento\Framework\App\Action\Action
{
    /**
     * Customer session model
     *
     * @var \Magento\Customer\Model\Session
     */
    protected $_customerSession;
    protected $resultFactory;
    
    /*
     * @var \Sts\SmartRoute\Model\PaymentMethod
     */
    protected $_paymentMethod;
    protected $_checkoutSession;
    protected $checkout;
    /**
     *
     * @var \Magento\Quote\Model\QuoteManagement
     */
    protected $cartManagement;
    protected $orderRepository;
    protected $_scopeConfig;
    
    protected $urlBuilder;

    /**
     * @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,
        \Sts\SmartRoute\Model\PaymentMethod $paymentMethod,
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        CartManagementInterface $cartManagement,
        \Magento\Framework\Controller\ResultFactory $resultFactory,
        \Magento\Framework\Url $urlBuilder
    ) {
        $this->_customerSession = $customerSession;
        parent::__construct($context);
        $this->_paymentMethod = $paymentMethod;
        $this->_checkoutSession = $checkoutSession;
        $this->cartManagement = $cartManagement;
        $this->orderRepository = $orderRepository;
        $this->_scopeConfig = $scopeConfig;
        $this->resultFactory = $resultFactory;
        $this->urlBuilder = $urlBuilder;
    }


    
    public function execute()
    {
        
        $order = $this->_checkoutSession->getLastRealOrder();
        $redirectionData = $this->getRedirectionData($order);
        
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $getLocale = $objectManager->get('Magento\Framework\Locale\Resolver');
        $haystack  = $getLocale->getLocale(); 
        $lang = strstr($haystack, '_', true);          
        
        $viewData = array();
        $viewData['redirect_url'] = $redirectionData['url'];
        $viewData['redirect_fields'] = $redirectionData['fields'];
        $viewData['lang'] = $lang;
        
        $pageResult = $this->resultFactory->create(ResultFactory::TYPE_PAGE);        
        $pageResult->addHandle('smartroute_payment_redirect');        
           
        $pageResult->getLayout()->getBlock('smartroute_redirectform')->setData($viewData);
        
        return $pageResult;                  
    }
    
    
    /**
     * getting redirection data used inside smartRoute redirect method
     * @return array
     */
    public function getRedirectionData(Order $order) {
        
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $getLocale = $objectManager->get('Magento\Framework\Locale\Resolver');
        $haystack  = $getLocale->getLocale(); 
        $lang = strstr($haystack, '_', true); 

        $secretKey = $this->_scopeConfig->getValue('payment/smartroute/secret_key');
        $transaction_id = (int) (microtime(true) * 1000);

        
        $totalAmount = $this->_paymentMethod->getTotalAmountForGateway($order);
        $currencyIso = $this->_paymentMethod->getCurrencyIsoNumberFromCode($order->getBaseCurrencyCode());
        $this->_paymentMethod->savePaymentTransaction($order, $transaction_id);

        $parameters = array();
        $parameters['TransactionID'] = $transaction_id;
        $parameters['MerchantID'] = $this->_scopeConfig->getValue('payment/smartroute/merchant_id');
        $parameters['Amount'] = $totalAmount;
        $parameters['CurrencyISOCode'] = $currencyIso;
        $parameters['MessageID'] = "1";
        $parameters['Quantity'] = "1";
        $parameters['Channel'] = "0";
        //fill some optional parameters
        $parameters['Language'] = $lang;
        $parameters['ThemeID'] = "1000000001";
        $parameters['ResponseBackURL'] = $this->urlBuilder->getUrl('stssmartroute/payment/redirectResponse');
        $parameters['Version'] = "1.0";
        $parameters['ItemID'] = $this->_scopeConfig->getValue('payment/smartroute/item_id');       
        //Create an Ordered String of The Parameters string with Secret Key by ksort
        ksort($parameters);
        $orderedString = $secretKey;
        foreach ($parameters as $param) {
            $orderedString .= $param;
        }

        //Generate SecureHash with SHA256
        $secureHash = hash('sha256', $orderedString, false);

        //Step 2: Prepare Payment Request and Send It to Redirect PHP  Page (To Send a Post Request)
        $attributesData = array();
        $attributesData['TransactionID'] = $transaction_id;
        $attributesData['MerchantID'] = $this->_scopeConfig->getValue('payment/smartroute/merchant_id');
        $attributesData["Amount"] = $totalAmount;
        $attributesData["CurrencyISOCode"] = $currencyIso;
        $attributesData["MessageID"] = "1";
        $attributesData["Quantity"] = "1";
        $attributesData["Channel"] = "0";

        $attributesData["Language"] = $lang;
        $attributesData["ThemeID"] = "1000000001";
        $attributesData['ItemID'] = $this->_scopeConfig->getValue('payment/smartroute/item_id');
        // if this url is configured for the merchant it's not required, else it is required
        $attributesData["ResponseBackURL"] = $this->urlBuilder->getUrl('stssmartroute/payment/redirectResponse');
        $attributesData["Version"] = "1.0";
        $attributesData["RedirectURL"] = $this->_scopeConfig->getValue('payment/smartroute/redirect_payment_url');
        // set secure hash in the request
        $attributesData["SecureHash"] = $secureHash;

        return ['fields' => $attributesData, 'url' => $this->urlBuilder->getUrl('stssmartroute/payment/redirectPage')];
    }
}


