<?php
// ... (previous code remains unchanged)
require_once 'GrayquestPaymentGateway.php';
require_once("./config/QueryBuilder.php");
class PaymentRequest
{
    private $conn;
    private $queryBuilder;   
    private $grayquestObj;
    private $translationMsg;

    public function __construct($conn)
    {
        $this->conn = $conn;
        $this->queryBuilder = new QueryBuilder($conn);       
        $this->grayquestObj = new GrayquestPaymentGateway();
        $this->translationMsg =  json_decode(TRANSLATION_MSG, true);

    }

    public function paymentRequest($data, $screenName, $tableName, $merchantDetails)
    {
        if ($data['gatewayConfig']) {
            echo '<div class="col-md-12 text-center alert alert-warning">
                        <h4>'.$this->translationMsg['TXN_ID_ALREADY_GENERATED'].'</h4>
                    </div>';
        } else {          
               
            $gatewayJSON = <<<GATEWAYJSON
            {
                "client_id": "{$merchantDetails['clientId']}",
                "client_secret": "{$merchantDetails['clientSecret']}",
                "api_key": "{$merchantDetails['apiKey']}",
                "environment": "{$merchantDetails['environment']}",
                "slug":"{$merchantDetails['slug']}",
                "url":"{$merchantDetails['productionURL']}",
                "paymentStatusUrl":"{$merchantDetails['fetchEmiURl']}"                                
            }
            GATEWAYJSON;
            $txnId      = 'ORD' . time() . mt_rand(100, 999);
            $activeGateway = $data['paymentOption'];
            $gateway = json_decode($gatewayJSON, true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                echo 'JSON Error: ' . json_last_error_msg();
                die();
            }
            $updateData = [
                'gatewayConfig' => $gatewayJSON,
                'txnId'=> $txnId,
                'academyLocationId' => $data['academyLocationId'],
                'paymentOption' => $activeGateway,
                'paymentDate' => date('Y-m-d H:i:s')
            ];
            $where = ['id' => $data['id']];
            $result = $this->queryBuilder->update($tableName, $updateData, $where);               
            if ($result == 1) {
                $paymentRequestColumnData = [
                    'screen' => $screenName,
                    'txnId' => $txnId,
                    'paymentDate' => date('Y-m-d H:i:s'),
                    'onlinePaymentId' => !empty($data['onlinePaymentId']) ? $data['onlinePaymentId'] : (isset($data['onlinePaymentId']) ? 0 : NULL),
                    'paymentId' => $data['id'],
                    'payment_gateway' => $activeGateway
                ];
                $this->queryBuilder->insert('payment_request', $paymentRequestColumnData);

                $where = ['id' => $data['id']];
                $paymentDetails = $this->queryBuilder->selectById($tableName, '*', $where);
                $gatewayInfo = '';
                if ($paymentDetails && $paymentDetails['gatewayConfig']) {
                    $gatewayInfoArr = json_decode($paymentDetails['gatewayConfig'], true);
                    
                        if (isset($gatewayInfoArr['client_id']) && $gatewayInfoArr['client_id'] &&
                            isset($gatewayInfoArr['client_secret']) && $gatewayInfoArr['client_secret'] &&
                            isset($gatewayInfoArr['api_key']) && $gatewayInfoArr['api_key'] &&
                            isset($gatewayInfoArr['slug']) && $gatewayInfoArr['slug'] &&
                            isset($gatewayInfoArr['environment']) && $gatewayInfoArr['environment'] && 
                            isset($gatewayInfoArr['url']) && $gatewayInfoArr['url'] && 
                            isset($gatewayInfoArr['paymentStatusUrl']) && $gatewayInfoArr['paymentStatusUrl'] )  {
                            $gatewayInfo = 'EXIST';
                        }
                    
                }
                if (!$paymentDetails || $paymentDetails == 0 || $gatewayInfo == '') {
                    echo '<div class="col-md-12 text-center alert alert-warning">
                            <h4>'.$this->translationMsg['INVALID_PAYMENT_GATEWAY_CONFIGURATION'].'</h4>
                        </div>';
                } else {
                    $paymentDetails['screenName'] = $screenName;
                    
                    $paymentRequest = $this->grayquestObj->createOrder($paymentDetails, $gateway);
                    
                    $updateData = ['paymentRequest' => json_encode($paymentRequest)];
                    $where = ['id' => $data['id']];
                    $result = $this->queryBuilder->update($tableName, $updateData, $where);
                    echo $paymentRequest;
                }
            }else {
                echo '<div class="col-md-12 text-center alert alert-warning">
                       <h4>'.$this->translationMsg['TRANSACTION_ERROR'].'</h4>
                      </div>';
            }              
        }
    }

    

    public function onlinePaymentReceipt($paymentRequest, $connMain)
    {        
        $onlinePaymentId = $paymentRequest['onlinePaymentId'];
        $tableName = 'online_payment';
        require_once "academia/onlinePayment.php";
        $onlinePaymentObj = new OnlinePayment();
        $onlinePaymentObj->setConnection($this->conn, $connMain);
        $where = ['id' => $paymentRequest['paymentId'], 'onlinePaymentId' => $onlinePaymentId];
        $onlinePaymentInfo = $this->queryBuilder->selectById($tableName, '*', $where);              
        if ($onlinePaymentInfo) {
            if ($onlinePaymentInfo['formSubmissionStatus'] != 1) {
                
                if($onlinePaymentInfo['paymentStatus'] == 'EMI FORM SUBMITTED')
                {
                 $orderInfo = $this->grayquestObj->fetchEmiStatus($onlinePaymentInfo);

                }
                else
                {
                $orderInfo = $this->grayquestObj->fetchOrder($onlinePaymentInfo); 
                }
                     
                if (isset($orderInfo['grayquestId']) && $orderInfo['txnId'] == $onlinePaymentInfo['txnId']  && $orderInfo['transactionStatus'] == 'PAID' || $orderInfo['transactionStatus'] == 'Disbursed' ) {
                    $updateData = [
                        'notificationResponse' => json_encode($orderInfo['fullResponse']),
                        'formSubmissionStatus' => 1,                        
                        'paymentStatus' => $orderInfo['transactionStatus']
                    ];                   
                    $where = ['id' => $paymentRequest['paymentId']];
                    $this->queryBuilder->update($tableName, $updateData, $where);
                    $response = $onlinePaymentObj->createReceipt($onlinePaymentInfo['onlinePaymentId'], $orderInfo['txnId'], $orderInfo['transactionStatus']);                   
                    if ($response == 'SUCCESS') {
                        $updateData = ['receiptStatus' => $response];
                        $where = ['id' => $paymentRequest['paymentId']];
                        $result = $this->queryBuilder->update($tableName, $updateData, $where);
                        echo '<div class="col-md-12 text-center alert alert-success">
                                    <h4>'.str_replace("[TRANSACTION_ID]",$orderInfo['txnId'], $this->translationMsg['TRANSACTION_SUCCESS_RECEIPT_GENERATED']).'</h4>
                            </div>';
                    } else {
                        echo '<div class="col-md-12 text-center alert alert-success">
                                    <h4>'. str_replace("[TRANSACTION_ID]",$orderInfo['txnId'], $this->translationMsg['TRANSACTION_SUCCESS_RECEIPT_NOT_GENERATED']).'</h4>
                         </div>';
                    }
                } else {
                    $updateData = [
                        'paymentStatus' => isset($orderInfo['error']) ? $orderInfo['error'] : 'FAILED',
                        'notificationResponse' => json_encode($orderInfo),
                        'formSubmissionStatus' => 1
                    ];
                    $where = ['id' => $paymentRequest['paymentId']];
                    $this->queryBuilder->update($tableName, $updateData, $where);
                    echo '<div class="col-md-12 text-center alert alert-warning">
                                <h4>'.str_replace("[ORDER_STATUS]",$orderInfo['error'], $this->translationMsg['TRANSACTION_NOT_SUCCESS']).'</h4>
                    </div>';
                }
            } else {
                echo '<div class="col-md-12 text-center alert alert-warning">
                         <h4>'.$this->translationMsg['TRANSACTION_ERROR'].'1w</h4>
                </div>';
            }
        } else {
            echo '<div class="col-md-12 text-center alert alert-warning">
                    <h4>'.$this->translationMsg['TRANSACTION_ERROR'].'q</h4>
            </div>';
        }
    }
}
?>