<?php

namespace Sts\SmartRoute\Controller\Payment;

use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\Payment\Transaction;
use Magento\Store\Model\ScopeInterface;
use Magento\Framework\Controller\ResultFactory;
use Psr\Log\LoggerInterface;
use Magento\Framework\App\CsrfAwareActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\Request\InvalidRequestException;
class DirectPost extends \Magento\Framework\App\Action\Action implements CsrfAwareActionInterface{

    /**
     * Customer session model
     *
     * @var \Magento\Customer\Model\Session
     */
    protected $_customerSession;
    protected $_checkoutSession;
    protected $redirectFactory;
    protected $resultFactory;
    protected $_scopeConfig;
    protected $_orderFactory;    
    protected $orderSender;
    protected $request;
    protected $_paymentMethod;
    protected $urlBuilder; 
    protected $logger; 
    
    /**
     *
     * @var \Magento\Sales\Model\Order\Payment\TransactionFactory 
     */
    protected $_transactionFactory;


    /**
     * 
     * @param \Magento\Framework\App\Request\Http $request
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Framework\Url $urlBuilder
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param \Sts\SmartRoute\Model\PaymentMethod $paymentMethod
     * @param \Magento\Checkout\Model\Session $checkoutSession
     * @param \Magento\Framework\Controller\Result\RedirectFactory $redirectFactory
     */
    public function __construct(
            \Magento\Framework\App\Request\Http $request, 
            \Magento\Framework\App\Action\Context $context, 
            \Magento\Framework\Url $urlBuilder,                         
            \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, 
            \Sts\SmartRoute\Model\PaymentMethod $paymentMethod,
            \Magento\Checkout\Model\Session $checkoutSession,
            \Magento\Framework\Controller\Result\RedirectFactory $redirectFactory,
            \Magento\Framework\Controller\ResultFactory $resultFactory,
            LoggerInterface $logger
    ) {
        $this->_request = $request;
        parent::__construct($context);
        $this->_scopeConfig = $scopeConfig;
        $this->urlBuilder = $urlBuilder;                  
        $this->_paymentMethod = $paymentMethod;
        $this->_checkoutSession = $checkoutSession;
        $this->redirectFactory = $redirectFactory;
        $this->resultFactory = $resultFactory;
        $this->logger = $logger;
    }


    public function execute() {
                
        $order = $this->_checkoutSession->getLastRealOrder();
        
        $viewData = [];                        
        $viewData['paymentParams'] = $this->prepareDirectPostRequest($order);
        $viewData['paymentTypeAllowed'] = $this->_scopeConfig->getValue('payment/smartroute/method_type');                                    

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

        $pageResult = $this->resultFactory->create(ResultFactory::TYPE_PAGE);
        $pageResult->addHandle('smartroute_payment_directpost_payment');
        $pageResult->getLayout()->getBlock('smartroute_direct_post_form_selectpayment')->setData($viewData);

        return $pageResult;
    }

    /**
     * prepare direct post methods data
     * @param Transaction $transaction
     * @param string $secureHash
     * @return array
     */
    protected function prepareDirectPostRequest(Order $order){
                
        $totalAmount = $this->_paymentMethod->getTotalAmountForGateway($order);
        $currencyIso = $this->_paymentMethod->getCurrencyIsoNumberFromCode($order->getBaseCurrencyCode());
        
        $transactionId = (int) (microtime(true) * 1000);
        $this->_paymentMethod->savePaymentTransaction($order, $transactionId);        
        
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $getLocale = $objectManager->get('Magento\Framework\Locale\Resolver');
        $haystack  = $getLocale->getLocale(); 
        $lang = strstr($haystack, '_', true); 
        
        $paymentParameters = [];
        $paymentParameters["Amount"] = $totalAmount;
        $paymentParameters["Channel"] = "0";
        $paymentParameters["CurrencyISOCode"] = $currencyIso;
        $paymentParameters["Language"] = $lang;
        $paymentParameters["MerchantID"] = $this->_scopeConfig->getValue('payment/smartroute/merchant_id');
        $paymentParameters["MessageID"] = "1";
        $paymentParameters["PaymentDescription"] = "MagentoPayment";        
        $paymentParameters["Quantity"] = "1";
        $paymentParameters["ResponseBackURL"] = $this->urlBuilder->getUrl('stssmartroute/payment/directPostResponse');                
        $paymentParameters["ThemeID"] = "1000000001";                        
        $paymentParameters["TransactionID"] = $transactionId;                        
        $paymentParameters["Version"] = "1.0"; //make constant
        $paymentParameters['ItemID'] = $this->_scopeConfig->getValue('payment/smartroute/item_id');
        
        //calculate secured hashes
        $paymentParameters["PaymentMethod"] = 1; //creditcard
        $secureHashCreditCard = $this->calculateSecureHash($paymentParameters);        

        $paymentParameters["PaymentMethod"] = 2; //sadad
        $secureHashSadad = $this->calculateSecureHash($paymentParameters);
        
        $paymentParameters["secureHashCreditCard"] = $secureHashCreditCard;
        $paymentParameters["secureHashSadad"] = $secureHashSadad;

        $paymentParameters["RedirectURL"] = $this->_scopeConfig->getValue('payment/smartroute/redirect_payment_url');
        $paymentParameters['SadadOlpId'] = "";
                    
        return $paymentParameters;
    }

    private function calculateSecureHash(array $paymentParameters){
        $secretKey = $this->_scopeConfig->getValue('payment/smartroute/secret_key');

        ksort($paymentParameters);
        $orderedString = $secretKey;
        foreach($paymentParameters as $param){
            $orderedString .= $param;
        }
        $this->logger->info('smart route for ordered string payment#'.$paymentParameters['PaymentMethod'].' : '.$orderedString);
        //Generate SecureHash with SHA256
        $secureHash = hash('sha256',$orderedString,false);        
        $this->logger->info('smart route for hash# '.$paymentParameters['PaymentMethod'].' : '.$secureHash);
        
        return $secureHash;
    }
    
    public function createCsrfValidationException(RequestInterface $request): ?InvalidRequestException
    {
        return null;
    }

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