<?php
require_once "./config/db_config.php";
require_once "./sdk/paytm/PaytmChecksum.php";

class PaytmPaymentGateway {

    public $domainURL;
    const CALLBACK_URL = '/paymentResponse.php';

    public function __construct()
    {
        $this->domainURL = domainURL;
    }

    public function createOrder($data)
    {
        $gatewayJson = json_decode($data['gatewayConfig'], true);
        $requiredKeys = ['MID', 'MerchantKey', 'currencyCode', 'baseURL', 'industryType', 'environment', 'Website','merchantReference'];
        foreach ($requiredKeys as $key) {
            if (empty($gatewayJson[$key])) {
                return ['status' => 'ERROR', 'message' => "Missing required gateway parameter: $key"];
            }
        }

        $merchantId = $gatewayJson['MID'];
        $merchantKey = $gatewayJson['MerchantKey'];
        $environment = $gatewayJson['environment'];
        $currencyCode = $gatewayJson['currencyCode'] ?? 'INR';        
        $paytmBaseUrl = $gatewayJson['baseURL'];
        $industryType = $gatewayJson['industryType'];
        $paytmWebsite = $gatewayJson['Website'];
        $merchantReference = $gatewayJson['merchantReference'];     
        $orderId = $data['txnId'];
        $amount = number_format($data['amount'], 2, '.', '');

         try {
            // Prepare Paytm transaction request
            $paytmParams = [
                'body' => [
                    'requestType' => 'Payment',
                    'mid' => $merchantId,
                    'websiteName' => $paytmWebsite, // Adjust based on environment
                    'orderId' => $orderId,
                    'callbackUrl' => $this->domainURL . self::CALLBACK_URL,
                    'txnAmount' => [
                        'value' => $amount,
                        'currency' => $currencyCode,
                    ],
                    'userInfo' => [
                        'custId' => $merchantReference,                       
                    ],
                    "extendInfo"    => array(
                        "mercUnqRef"    => $merchantReference
                    )
                ],
                'head' => [
                    'signature' => '',
                ],
            ];

            // Generate checksum
            $checksum = PaytmChecksum::generateSignature(json_encode($paytmParams['body'], JSON_UNESCAPED_SLASHES), $merchantKey);
            $paytmParams['head']['signature'] = $checksum;

            // Initiate transaction API call
            $url = $paytmBaseUrl . '/theia/api/v1/initiateTransaction?mid=' . $merchantId . '&orderId=' . $orderId;
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($paytmParams, JSON_UNESCAPED_SLASHES));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);           
            $responseData = json_decode($response, true);            
            if ($httpCode === 200 && isset($responseData['body']['resultInfo']['resultStatus']) && $responseData['body']['resultInfo']['resultStatus'] === 'S') {
                return [
                    'status' => 'SUCCESS',
                    'url' => $paytmBaseUrl,                 
                    'data' => $responseData,
                    'token' => $responseData['body']['txnToken'],
                    'orderId' => $orderId,
                    'mid'=>  $merchantId                
                ];
            } else {
                return [
                    'status' => 'ERROR',
                    'message' => $responseData['body']['resultInfo']['resultMsg'] ?? 'Failed to initiate transaction',
                    'data' => $responseData,
                ];
            }
        } catch (Exception $e) {
            return ['status' => 'ERROR', 'message' => $e->getMessage()];
        }
    }

    public function fetchOrder($data)
    {
        $gatewayJson = json_decode($data['gatewayConfig'], true);        
        $requiredKeys = ['MID', 'MerchantKey','baseURL'];
        foreach ($requiredKeys as $key) {
            if (empty($gatewayJson[$key])) {
                return ['status' => 'ERROR', 'message' => "Missing required gateway parameter: $key"];
            }
        }       
        $orderId = $data['txnId']; // Paytm uses orderId instead of payUReference
        $merchantId = $gatewayJson['MID'];
        $merchantKey = $gatewayJson['MerchantKey'];  
        $paytmBaseUrl = $gatewayJson['baseURL'];
        try {
            // Prepare status check request
            $paytmParams = [
                'body' => [
                    'mid' => $merchantId,
                    'orderId' => $orderId,
                ],
                'head' => [
                    'signature' => '',
                ],
            ];

           
            $checksum = PaytmChecksum::generateSignature(json_encode($paytmParams['body'], JSON_UNESCAPED_SLASHES), $merchantKey);
            $paytmParams['head']['signature'] = $checksum;           
            $url = $paytmBaseUrl . '/v3/order/status';
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($paytmParams, JSON_UNESCAPED_SLASHES));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            $responseData = json_decode($response, true);
            if ($httpCode === 200 && isset($responseData['body']['resultInfo']['resultStatus'])) {
                $transactionState = $responseData['body']['resultInfo']['resultStatus'];
                return [
                    'status' => 'SUCCESS',
                    'orderId' => $orderId, 
                    'transactionState' => $transactionState,
                    'jsonResponse' => $responseData,
                ];
            } else {
                return [
                    'status' => 'SUCCESS',
                    'jsonResponse' => $responseData,
                    'transactionState' => 'FAILED'
                ];
            }
        } catch (Exception $e) {
            return ['status' => 'ERROR', 'message' => $e->getMessage()];
        }
    }
}