<?php
require_once("./config/db_config.php");
class AdityaBirlaGateway
{    
    public $domainURL;
    private $createOrderUrl = 'api/v1/order/create';
    private $fetchOrderUrl = 'api/v1/order/query';    
    public const GCM_TAG_LENGTH = 16;
    function __construct()
    {
        $this->domainURL = domainURL;
    }
    public static function encrypt($plaintext, $key, $IV)
    {
        try {
            $cipher = "AES-256-GCM";
            $ciphertext = openssl_encrypt(
                $plaintext,
                $cipher,
                $key,
                OPENSSL_RAW_DATA,
                $IV,
                $tag,
                "",
                self::GCM_TAG_LENGTH
            );
            $encryptedText = base64_encode($ciphertext . $tag);
            return $encryptedText;
        } catch (Exception $e) {
            // echo "Encryption Error: " . $e->getMessage();
            return null;
        }
    }
    public static function decrypt($ciphertext, $key, $IV)
    {
        try {
            $cipher = "AES-256-GCM";
            $decodedCiphertext = base64_decode($ciphertext);
            $tag = substr($decodedCiphertext, -self::GCM_TAG_LENGTH);
            $ciphertext = substr($decodedCiphertext, 0, -self::GCM_TAG_LENGTH);
            $plaintext = openssl_decrypt(
                $ciphertext,
                $cipher,
                $key,
                OPENSSL_RAW_DATA,
                $IV,
                $tag
            );
            return $plaintext;
        } catch (Exception $e) {
            // echo "Decryption Error: " . $e->getMessage();
            return null;
        }
    }

    public function createOrder($data)
    {
        $gatewayJson = json_decode($data['gatewayConfig'], true);
        $merchantId = $gatewayJson['merchantId'];
        $environment = $gatewayJson['environment'];
        $key = $gatewayJson['key'];
        $IV = $gatewayJson['iv'];
        $orderId = $data['txnId'];
        $accountNo = $gatewayJson['accountNo'];
        $accountIfsc = $gatewayJson['accountIfsc'];
        $orderIdArr = explode("ABC", $orderId);
        if(isset($data['studentCode']))
        {
            $data['code'] = $data['studentCode'] ;
        }
        if(isset($data['phoneNo']))
        {
            $parts =  explode(' ' , $data['phoneNo']);
            if(count($parts) > 1 )
            {
                $data['phoneNo'] = end($parts);
            }
        }
        // "account_ifsc": "HDFC00004",   // TODO: Remove this line after getting new merchant details
        // "account_no": "632748494664",  // TODO: Remove this line after getting new merchant details
        $plaintext = '{
            "payment_data": {
                "account_ifsc": "'.$accountNo.'",
                "account_no": "'.$accountIfsc.'",
                "allowed_split_payment": "0",
                "amount": '.$data['amount'].',
                "customer_email": "' . $data['email'] . '",
                "customer_id": "' . $data['code'] . '",
                "customer_name": "' . $data['name'] . '",
                "customer_phone": "' . $data['phoneNo'] . '",
                "invoice_no": "INV'.end($orderIdArr).'",
                "merc_id": "' . $merchantId . '",
                "merc_order_date": "' . date('YmdHis') . '",
                "merc_order_id": "' . $orderId . '",
                "payment_mode": "",
                "order_desc": "",
                "order_source": "web",
                "return_url": "' . $this->domainURL . '/paymentResponse.php",
                "udf1": "",
                "udf2": ""
            }
        }';
        // echo $plaintext."<br>";
        // echo $environment . $this->createOrderUrl;
        $encryptedText = $this->encrypt($plaintext, $key, $IV);
        $orderjson = '{"content":"' . $encryptedText . '"}';
        $curl = curl_init();
        $header = array(
            'pl-traceid: ' . end($orderIdArr),
            'pl-timestamp: ' . date('YmdHis'),
            'pl-merc-id: ' . $merchantId,
            'Content-Type: application/json'
        );
        // print_r($header);
        // echo $orderjson;
        curl_setopt_array($curl, array(
            CURLOPT_URL => $environment . $this->createOrderUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $orderjson,
            CURLOPT_HTTPHEADER => $header,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_SSL_VERIFYPEER => false
        ));

        $response = curl_exec($curl);       
        curl_close($curl);
        $ciphertextArr = json_decode($response, true);
        if(isset($ciphertextArr['status']) && ($ciphertextArr['status'] == 500 || $ciphertextArr['status'] == 400)){
            return false;
        }
        $ciphertext = isset($ciphertextArr["content"]) ? $ciphertextArr["content"] : $ciphertextArr;
        $response = $this->decrypt($ciphertext, $key, $IV);
        return  json_decode($response, true);
    }

    public function fetchOrder($data) {

        $gatewayJson = isset($data['gatewayConfig'])? json_decode($data['gatewayConfig'], true):'';
        $paymentRequest =  isset($data['paymentRequest'])? json_decode($data['paymentRequest'],  true):'';
        if($gatewayJson){
            $merchantId = $gatewayJson['merchantId'] ?? '';
            $environment = $gatewayJson['environment'] ?? '';
            $key = $gatewayJson['key'] ?? '';
            $IV = $gatewayJson['iv'] ?? '';
        }else {
            return false;
        }
        $orderId = $data['txnId'];
        $orderIdArr = explode("ABC", $orderId);
        $orderjson = '{
            "merc_id": "'.$merchantId.'",
            "merc_order_id": "'.$orderId.'"
        }';
        $encryptedText = $this->encrypt($orderjson, $key, $IV);
        $orderjson = '{"content":"'.$encryptedText.'"}';
        $curl = curl_init();
        $header = array(
            'pl-traceid: '. end($orderIdArr),
            'pl-timestamp: '.date('YmdHis'),
            'pl-merc-id: '.$merchantId,
            'Content-Type: application/json');
        curl_setopt_array($curl, array(
          CURLOPT_URL => $environment.$this->fetchOrderUrl,
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => '',
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => 'POST',
          CURLOPT_POSTFIELDS => $orderjson,
          CURLOPT_HTTPHEADER => $header,
          CURLOPT_SSL_VERIFYHOST => false,
          CURLOPT_SSL_VERIFYPEER => false
        ));
       
        $response = curl_exec($curl);       
        curl_close($curl);
        $ciphertextArr= json_decode($response, true);
        if(isset($ciphertextArr['status']) && ($ciphertextArr['status'] == 500 || $ciphertextArr['status'] == 400)){
            return false;
        }
        $ciphertext = $ciphertextArr['content'];
        $encryptedText = $this->decrypt($ciphertext, $key, $IV);
        $result = json_decode($encryptedText, true);
        return $result;


    }
}
