<?php
require_once("./config/db_config.php");
require_once("./config/functionclass.php");
class BspPaymentGateway
{

    private $encryptionMethod = 'AES-256-CBC';
    public $domainURL;
    public $accessToken;
    private $ClassObject;
    private $nonsec;
    public function __construct()
    {        
        $this->domainURL = domainURL;        
    }
   
    public function createOrder($data)
    {
            
        $gatewayJson = json_decode($data['gatewayConfig'], true);
        $checkoutURL = $gatewayJson['checkoutURL'];
        $currencyCode = $gatewayJson['currencyCode'];
        $merchantKey = $gatewayJson['merchant_key']; 
        $customerFirstName = '';
		$customerLastName = '';
        if($data['name'])
        {
            $names = explode(' ', $data['name']);
            if(count($names) > 1)
            {
                $customerFirstName = $names[0];
                $customerLastName = $names[1];
            }
            else
            {
                $customerFirstName = $data['name'];
                $customerLastName = $data['name'];
            }
        }
        $orderId = $data['txnId'];
        $description = 'Order Initiate using order ID - '.$orderId;
        // $orderSignature = $orderId.'BSP'.rand(100,1000);
        $callbackUrl = $this->domainURL.'/paymentResponse.php?order_id='.$orderId.'&key='.$orderId;
        $orderDetails['ipgw_id'] = intval($orderId);
        $orderDetails['merchant_key'] = trim($merchantKey);
        $orderDetails['amount'] = number_format((float)$data['amount'], 2, '.', '');
        $orderDetails['customer_first_name'] = trim($customerFirstName);
        $orderDetails['customer_last_name'] = trim($customerLastName);
        $orderDetails['customer_email'] = trim($data['email']);
        $orderDetails['currency'] = trim($currencyCode);
        $orderDetails['description'] = trim($description);
        $orderDetails['callback_url'] = trim($callbackUrl);
        $orderDetails['callback_key'] = $orderId;
        $orderDetails['orderId'] = $orderId;
        $key = substr($merchantKey,0,16);
        $iv = substr($merchantKey,0,16);
        $encryptedData = base64_encode(openssl_encrypt(json_encode($orderDetails),"aes-128-cbc",$key,OPENSSL_RAW_DATA,$iv));
        $encryptedIV = base64_encode($iv);
        $encryptedPayload = $encryptedData.":".$encryptedIV;
        return [
            'encryptedPayload' => $encryptedPayload,
            'checkoutURL' => $checkoutURL,
            'merchantKey' => $merchantKey,
            'callbackUrl' => $callbackUrl
        ];

    }

    private function getDecryptedURL($merchantKey, $encryptedPayload)
    {
        try
        {

            $key = substr($merchantKey, 0, 32);
            $iv = substr($merchantKey, 0, 16);
            if (strlen($iv) !== 16) {
                throw new Exception("Invalid IV length. It must be exactly 16 bytes.");
            }
            $decryptedData = openssl_decrypt($encryptedPayload, $this->encryptionMethod, $key, 0, $iv);
            if ($decryptedData === false) {
                throw new Exception("Decryption failed.");
            }
            return $decryptedData;

        }
        catch(Exception $e)
        {
            return null;
        }

    }
    public function fetchOrder($data)
    {
        
        $encryptedPayload = trim($data['encryptedData']);

        $gatewayJson = json_decode($data['gatewayConfig'], true);     
        
        $merchantKey = $gatewayJson['merchant_key']; 

        $decryptedParams = $this->getDecryptedURL($merchantKey, $encryptedPayload);
        
        parse_str(substr($decryptedParams, 1), $orderData);
        $orderData['encryptedData'] = $data['encryptedData'];
        return $orderData;


    }

}