<?php

namespace Sts\SmartRoute\Controller\Payment;

use \Magento\Sales\Model\Order;
use \Magento\Store\Model\ScopeInterface;

class RedirectResponse extends \Magento\Framework\App\Action\Action {

    /**
     * Customer session model
     *
     * @var \Magento\Customer\Model\Session
     */
    protected $_customerSession;
    protected $resultPageFactory;
    protected $_scopeConfig;
    protected $_orderFactory;
    private $invoiceService;
    protected $orderSender;    
    protected $_paymentMethod;
    /**
     *
     * @var \Magento\Sales\Model\Order\Payment\TransactionFactory
     */
    protected $paymentTransactionFactory;
    protected $logger;

    const PAYMENT_STATUS_SUCCESS = '00000';

    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Customer\Model\Session $customerSession
     */
    public function __construct(            
            \Magento\Framework\App\Action\Context $context, 
            \Magento\Sales\Model\OrderFactory $orderFactory, 
            \Magento\Sales\Model\Service\InvoiceService $invoiceService, 
            \Magento\Sales\Model\Order\Email\Sender\OrderSender $orderSender, 
            \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, 
            \Sts\SmartRoute\Model\PaymentMethod $paymentMethod,
            \Magento\Sales\Model\Order\Payment\TransactionFactory $paymentTransactionFactory,
            \Psr\Log\LoggerInterface $logger
    ) {        
        parent::__construct($context);
        $this->_scopeConfig = $scopeConfig;
        $this->_orderFactory = $orderFactory;
        $this->paymentTransactionFactory = $paymentTransactionFactory;
        $this->invoiceService = $invoiceService;        
        $this->orderSender = $orderSender;
        $this->_paymentMethod = $paymentMethod;
        $this->logger = $logger;
    }


    public function execute() {

        $secretKey = $this->_scopeConfig->getValue('payment/smartroute/secret_key');

        // get All Request Parameters
        $parameterNames = $this->getRequest()->getParams();        
        $this->logger->info('smartroute redirect response parameters: '.json_encode($parameterNames));
        
        $order = null;
        $transaction = null;
        
        if(isset($parameterNames['Response_TransactionID'])){            
            $transactionFactory = $this->paymentTransactionFactory->create();
            $transaction = $transactionFactory->load($parameterNames['Response_TransactionID'], 'txn_id');
            if($transaction){
                $order = $transaction->getOrder();
            }
        }
        
        if(!$order){        
            $this->messageManager->addErrorMessage('Order not found');
            return $this->_redirect('stssmartroute/payment/cancel',[                   
                        'statusDesc'=> 'Order not found',
                        'statusCode'=> ''                     
                ]);            
        }
        
        // store all response Parameters to generate Response Secure Hash
        // and get Parameters to use it later in your Code
        $responseParameters = $parameterNames;
        // get the received secure hash from result map
        $receivedSecureHash = isset($responseParameters['Response_SecureHash'])?
                $responseParameters['Response_SecureHash']:null;
        
        unset($responseParameters['Response_SecureHash']);

        //order parameters by key using ksort
        ksort($responseParameters);
        $orderedString = $secretKey;
        foreach ($responseParameters as $key => $param) {
            if($param !== 'null'){
                if(strpos($key,'Status')!== false){ //remove spaces from status directives
                    $param = urlencode($param);
                }
                $orderedString .= $param;
            }
        }
        $this->logger->info('smartroute redirect ordered string: '.$orderedString);
        // Generate SecureHash with SHA256
        $secureHash = hash('sha256', $orderedString, false);

        // Now that we have the map, order it to generate secure hash and compare it with the received one
        if ($receivedSecureHash !== $secureHash) {
            // If they are not equal then the response shall not be accepted
            $this->logger->info('smartroute redirect response secure hash not match: '
                    .$receivedSecureHash." != ".$secureHash);
            $inquiryRet = $this->_paymentMethod->processAPIInquiry($order);
            if($inquiryRet['status'] === self::PAYMENT_STATUS_SUCCESS){
                // If they are not equal then the response shall not be accepted
                $this->messageManager->addSuccessMessage(__($inquiryRet['statusDescription']));
                $this->_redirect('stssmartroute/payment/paymentComplete',[                    
                    'statusCode'=> $inquiryRet['status'],
                    'statusDesc'=> __($inquiryRet['statusDescription']),
                    'TransactionId' => $responseParameters['Response_TransactionID'],
	            'inquiry' => 1,
                ]);
            }else{
                $this->messageManager->addErrorMessage(__($inquiryRet['statusDescription']));
                $this->_redirect('stssmartroute/payment/cancel',[                    
                    'statusDesc'=> __($inquiryRet['statusDescription']),
                    'statusCode'=> '',
                    'TransactionId' => $responseParameters['Response_TransactionID'],
	            'inquiry' => 1,
                ]);
            }           
            
        } else {            
            // Complete the Action get other parameters from result map and do
            // your processes
            // Please refer to The Integration Manual to see the List of The
            // Received Parameters    
            $responseStatus = $this->getRequest()->getParam('Response_StatusCode');            
            if ($responseStatus == self::PAYMENT_STATUS_SUCCESS) {
                $this->logger->info('smartroute redirect marking order#'.$order->getId().' as sucessfull');
                $this->_paymentMethod->markOrderAsSuccessfull($order,$parameterNames['Response_TransactionID']);
                $this->messageManager->addSuccessMessage(__($parameterNames['Response_StatusDescription']));                
                $this->_redirect('stssmartroute/payment/paymentComplete',[                    
                    'statusCode'=> $parameterNames['Response_StatusCode'],
                    'statusDesc'=> __($parameterNames['Response_StatusDescription']),
                    'TransactionId' => $parameterNames['Response_TransactionID']
                ]);                
            }else{
                $this->logger->info('smartroute redirect marking order#'.$order->getId().' as cancelled');                
                $this->messageManager->addErrorMessage(__($parameterNames['Response_StatusDescription']));
                $this->_redirect('stssmartroute/payment/cancel',[                    
                    'statusCode'=> $parameterNames['Response_StatusCode'],
                    'statusDesc'=> $parameterNames['Response_StatusDescription'],
                    'TransactionId' => $parameterNames['Response_TransactionID']
                ]);
            }
        }
        
        $this->getResponse()->sendResponse(json_encode(['success'=>'order status updated, status='.$order->getStatus()]));
    }

}
